public
Last active

Function to escape single and double quotes in XPath queries using PHP

  • Download Gist
xpath_escape.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
<?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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.