Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Function to escape single and double quotes in XPath queries using PHP
<?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

This comment has been minimized.

Copy link

commented Mar 3, 2013

I wrote a more efficient version: https://gist.github.com/thomasbachem/5076669

@whatthejeff

This comment has been minimized.

Copy link

commented Apr 9, 2013

@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
You can’t perform that action at this time.