xpath - PHP DOMXPath works with double quotes fails with single quotes -
xpath - PHP DOMXPath works with double quotes fails with single quotes -
i wrote little script extracts info web site using php's domxpath
class. query <div class="sku" />
, execute substring-before
on result. result contains text, non breaking spaces, line break , more text. i'm trying cutting before \r\n
. works fine when utilize next query:
$query = "substring-before(//div[@class='sku'],'\xc2\xa0\xc2\xa0\r\n')";
but fails alter quotes (which shouldn't create difference):
$query = 'substring-before(//div[@class="sku"],"\xc2\xa0\xc2\xa0\r\n")';
or
$query = 'substring-before(//div[@class=\'sku\'],\'\xc2\xa0\xc2\xa0\r\n\')';
how possible , how can overcome this?
live illustration here: http://codepad.viper-7.com/r1rcaj
the style of quotes makes difference because when string enclosed in double-quotes php interpret more escape sequences special characters - including you're using non-breaking space \xc2\xa0
, carriage homecoming \r
, , newline \n
.
when have these enclosed in single-quotes '\xc2\xa0\r\n'
, in sec 2 queries, php treats them literal characters - backslash, x, c, 2... etc.
a little syntax highlighting may help show off, escape sequences in orange:
if string has escape sequences in literal characters, , there's no way corrected*, you're in kinda dirty position of replacing them yourself.
this preg_replace_callback()
take care of sort of sequences in example, , it's trivial extend rest of escape sequences supported double-quotes:
// known good. $query1 = "substring-before(//div[@class='sku'],'\xc2\xa0\xc2\xa0\r\n')"; // known bad. $query2 = 'substring-before(//div[@class=\'sku\'],\'\xc2\xa0\xc2\xa0\r\n\')'; $query2 = preg_replace_callback( '/\\\\(?:[rn]|(?:x[0-9a-fa-f]{1,2}))/', function ($matches) { switch (substr($matches[0], 0, 2)) { case '\r': homecoming "\r"; case '\n': homecoming "\n"; case '\x': homecoming hex2bin(substr($matches[0], 2)); } }, $query2 ); var_dump($query1 === $query2); // equal?
output:
bool(true)
(*really, should fixed @ source.)
php xpath domxpath
Comments
Post a Comment