Voting

: six plus zero?
(Example: nine)

The Note You're Voting On

yuriscom at gmail dot com
13 years ago
I hope it will be helpful for someone:

I spent some time to solve the problem when you query a string with quotes inside.

Suppose you have:
$parameter = "aaa \"bbb\"";
$domxpath->query("//path[text()=\"".$parameter."\""];

In versions > 5.3.0 there is registerPhpFunctions where you can put an addslashes. But in older version you cannot do it in simple way.

So the solution is to use a concat function. So when you have a substring with " inside, wrap it with '. And when you have a substring with ', then wrap with in ".

The code is:

<?php
$dom
= new DOMDocument;
$dom->loadXML("<name>'bla' \"bla\" bla</name>");
$xpath = new DOMXPath($dom);
$nodeList = $xpath->query("//name[text()=concat(\"'bla' \" ,'\"bla\"' ,\" bla\")]");
?>

Below is the function that receives a string and returns a concat pattern for the xpath query.

<?php
function getPattern_MQ($pattern) {
// initiating an array of substrings
$ar = array();
// points to the current position in a string
$offset = 0;
$strlen = strlen($pattern);
while (
true) {
// find a position of quotes
$qPos = strpos($pattern, "\"", $offset);

if (!
$qPos) {
// no more quotes
$leftOver = $offset - $strlen;
if (
$leftOver < 0) {
$string = substr($pattern, $leftOver);
$ar[] = "\"" . $string . "\"";
}
break;
}
// add the whole substring before the quotes into the array
$ar[] = "\"" . substr($pattern, $offset, ($qPos - $offset)) . "\"";
// add the quotes wrapped with single quot
$ar[] = "'" . substr($pattern, $qPos, 1) . "'";
$offset = $qPos + 1;
}
// join the array to get: concat("aaa",'"',"bbb",'"');
$pattern = "concat(''," . join(",", $dynamicPatternsAr) . ")";
return
$pattern;
}
?>

<< Back to user notes page

To Top