Skip to content

Instantly share code, notes, and snippets.

@jaywilliams
Forked from chrif/xpath_escape.php
Created June 6, 2012 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaywilliams/2883026 to your computer and use it in GitHub Desktop.
Save jaywilliams/2883026 to your computer and use it in GitHub Desktop.
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
Copy link

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

@whatthejeff
Copy link

@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