dtc99987 2014-10-10 13:00
浏览 215
已采纳

PHP DOMXPath使用双引号失败,带单引号

I wrote a little script that extracts information from a web site using PHP's DOMXPath class.
I query for <div class="sku" /> and execute a substring-before on the result. The result contains text, non breaking spaces, a line break and more text.
So what I'm trying to do is cut before the &nbsp;&nbsp; . It works fine when I use the following query:

$query = "substring-before(//div[@class='sku'],'\xC2\xA0\xC2\xA0
')";

but fails as soon as I change the quotes (which shouldn't make any difference):

$query = 'substring-before(//div[@class="sku"],"\xC2\xA0\xC2\xA0
")';

or

$query = 'substring-before(//div[@class=\'sku\'],\'\xC2\xA0\xC2\xA0
\')';

How is this possible and how can I overcome this?

Live example here: http://codepad.viper-7.com/R1rCaj

  • 写回答

2条回答 默认 最新

  • dongye1934 2014-10-10 15:03
    关注

    The style of quotes makes a difference because when a string is enclosed in double-quotes PHP will interpret more escape sequences for special characters - including what you're using for non-breaking space \xC2\xA0, carriage return , and newline .

    When you have these enclosed in single-quotes '\xC2\xA0 ', like in your second two queries, PHP treats them as those literal characters - backslash, x, C, 2... etc.


    A little extra syntax highlighting may help show this off, escape sequences in orange:

    enter image description here


    If your string already has what would be escape sequences in it as literal characters, and there's no way to get that corrected*, you're in the kinda dirty position of replacing them yourself.

    This preg_replace_callback() will take care of the sort of sequences in your example, and it's trivial to extend to the rest of the escape sequences supported by double-quotes:

    // Known good.
    $query1 = "substring-before(//div[@class='sku'],'\xC2\xA0\xC2\xA0
    ')";
    
    // Known bad.
    $query2 = 'substring-before(//div[@class=\'sku\'],\'\xC2\xA0\xC2\xA0
    \')';
    
    $query2 = preg_replace_callback(
        '/\\\\(?:[rn]|(?:x[0-9A-Fa-f]{1,2}))/',
        function ($matches) {
            switch (substr($matches[0], 0, 2)) {
                case '':
                    return "";
                case '
    ':
                    return "
    ";
                case '\x':
                    return hex2bin(substr($matches[0], 2));
                }
        },
        $query2
    );
    
    var_dump($query1 === $query2); // Now equal?
    

    Output:

    bool(true)
    

    (*Really, you should get this fixed at the source.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真