-
-
Save jaywilliams/2883026 to your computer and use it in GitHub Desktop.
Function to escape single and double quotes in XPath queries using PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function xpathEscape($query, $default_delim = '"') | |
{ | |
if (strpos($query, $default_delim) === false) | |
return $default_delim . $query . $default_delim; | |
preg_match_all("#(?:('+)|[^']+)#", $query, $matches); | |
list($parts, $apos) = $matches; | |
foreach ($parts as $i => &$part) { | |
$delim = $apos[$i] ? '"' : "'"; | |
$part = $delim . $part . $delim; | |
} | |
// concat() must have two or more parts | |
if (count($parts) == 1) | |
$parts[] = $delim . $delim; | |
return 'concat(' . implode(',', $parts) . ')'; | |
} |
@thomasbachem, I don't think your version is necessarily more efficient. Implementing string searching in userland is typically less efficient. A more efficient alternative would be something along the lines of:
<?php
function xpathEscape($string)
{
if (strpos($string, "'") === false) {
return sprintf("'%s'", $string);
}
if (strpos($string, '"') === false) {
return sprintf('"%s"', $string);
}
return sprintf(
"concat('%s')", str_replace("'", "',\"'\",'", $string)
);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote a more efficient version: https://gist.github.com/thomasbachem/5076669