note 105692 added to domxpath.query
| From: | yuriscom at gmail dot com | Date: | Wed, 07 Sep 2011 17:29:37 +0000 |
| Subject: | note 105692 added to domxpath.query | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-183015@lists.php.net to get a copy of this message | ||
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:
$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.
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;
}
----
Server IP: 212.150.176.150
Probable Submitter: 91.143.233.99
----
Manual Page -- http://www.php.net/manual/en/domxpath.query.php
Edit -- https://master.php.net/note/edit/105692
Del: integrated -- https://master.php.net/note/delete/105692/integrated
Del: useless -- https://master.php.net/note/delete/105692/useless
Del: bad code -- https://master.php.net/note/delete/105692/bad+code
Del: spam -- https://master.php.net/note/delete/105692/spam
Del: non-english -- https://master.php.net/note/delete/105692/non-english
Del: in docs -- https://master.php.net/note/delete/105692/in+docs
Del: other reasons-- https://master.php.net/note/delete/105692
Reject -- https://master.php.net/note/reject/105692
Search -- https://master.php.net/manage/user-notes.php