dpsyssiv90846 2014-09-23 06:43
浏览 458
已采纳

双转义十六进制字符,即\\ x80 - \\ xFF

I have finally started to understand the context behind escaping hexadecimal characters such as \x80. The documentation talks about the escape sequences, but I can also see that some regular expression use double backslashes such as \\x80 - \\xFF.

What's the difference between \\x80 - \\xFF and \x80 - \xFF when using something like preg_replace ?

  • 写回答

2条回答 默认 最新

  • doutiaoku4495 2014-09-23 07:12
    关注

    When using preg_ functions, your string is parsed twice - first, by php compiler, and then by the PCRE engine. So if you have, for example:

    preg_match("/\x80/"....)
    

    the compiler turns it into

    preg_match("/�/"....) // let � be chr(80)
    

    and passes this to PCRE. When you have two slashes:

    preg_match("/\\x80/"....)
    

    the compiler turns the string into

    preg_match("/\x80/"....)
    

    and then it's the PCRE engine that converts this to the literal character .

    It doesn't make a difference in this particular case, but consider:

    preg_match("/\x5B/"....)
    

    after compilation

    preg_match("/[/"....)
    

    and PCRE fails, because of the dangling metacharacter [. Now if you escape the slash

    preg_match("/\\x5B/"....)
    

    it's compiled to

    preg_match("/\x5B/"....)
    

    which makes PCRE happy, because it understands that [ should be taken literally.

    How exactly php compiles your string depends on the quotes you use: double/single/heredocs/nowdocs. See docs for details. A simple rule of thumb is to use single quotes when possible, if you have to use doubles (for variable interpolation), escape everything twice, even if there's technically no need (e.g "\\b$word\\b").

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

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图