Skip to content

Instantly share code, notes, and snippets.

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

This comment has been minimized.

Copy link

thomasbachem commented Mar 3, 2013

I wrote a more efficient version:


This comment has been minimized.

Copy link

whatthejeff 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:

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.