Skip to content

Instantly share code, notes, and snippets.

@iaindooley
Created August 19, 2011 03:34
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save iaindooley/1155973 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,'\'') !== 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