Created
August 19, 2011 03:34
-
-
Save iaindooley/1155973 to your computer and use it in GitHub Desktop.
Function to escape single and double quotes in XPath queries using PHP
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 | |
function xpathEscape($query,$default_delim = '"') | |
{ | |
if((strpos($query,'\'') !== FALSE) || | |
(strpos($query,'"') !== FALSE)) | |
{ | |
$quotechars = array('\'','"'); | |
$parts = array(); | |
$current_part = ''; | |
foreach(str_split($query) as $character) | |
{ | |
if(in_array($character,$quotechars)) | |
{ | |
$parts[] = '\''.$current_part.'\''; | |
if($character == '\'') | |
$parts[] = '"'.$character.'"'; | |
else | |
$parts[] = '\''.$character.'\''; | |
$current_part = ''; | |
} | |
else | |
$current_part .= $character; | |
} | |
if($current_part) | |
$parts[] = '\''.$current_part.'\''; | |
$ret = 'concat('.implode(',',$parts).')'; | |
} | |
else | |
$ret = $default_delim.$query.$default_delim; | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment