Skip to content

Instantly share code, notes, and snippets.

@thomasbachem
Forked from jaywilliams/xpath_escape.php
Last active December 14, 2015 11:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasbachem/5076669 to your computer and use it in GitHub Desktop.
Save thomasbachem/5076669 to your computer and use it in GitHub Desktop.
<?php
/**
* Uses a concat() statement to provide proper escaping of single
* and double quotes for XPath strings.
*
* @link http://kushalm.com/the-perils-of-xpath-expressions-specifically-escaping-quotes
* @param string $value
* @return string
*/
function escapeXpathString($value) {
if(($dPos = strpos($value, '"')) === false) {
// No escaping needed if we use double quotes as delimeters
return '"' . $value . '"';
} elseif(($sPos = strpos($value, "'")) === false) {
// No escaping needed if we use single quotes as delimeters
return "'" . $value . "'";
}
// Start with the delimeter that suits the first found quote
$currentDelim = $sPos < $dPos ? '"' : "'";
$concat = 'concat(' . $currentDelim;
// Go thru each character of the value (no mb_*() functions needed)
for($i = 0, $l = strlen($value); $i < $l; ++$i) {
$char = $value[$i];
// If the current character conflicts with the current delimeter
if($char == $currentDelim) {
// Switch delimeter
$concat .= $currentDelim . ',';
$currentDelim = $char == '"' ? "'" : '"';
$concat .= $currentDelim . $char;
} else {
$concat .= $char;
}
}
$concat .= $currentDelim . ')';
return $concat;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment