Skip to content

Instantly share code, notes, and snippets.

@chrif
Forked from iaindooley/xpath_escape.php
Created February 10, 2012 02:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chrif/1785543 to your computer and use it in GitHub Desktop.
Save chrif/1785543 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;
}
return 'concat("",' . implode(',', $parts) . ')';
}
@jaywilliams
Copy link

This function has a bug, see my fork for details.
https://gist.github.com/2883026

@chrif
Copy link
Author

chrif commented Jun 6, 2012

You're right. Thank you for telling me.

@jaywilliams
Copy link

I see you've optimized my fork even further. I like your elegant solution to the problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment