-
-
Save thomasbachem/5076669 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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