dongshetao1814 2017-06-09 21:00
浏览 29
已采纳

在Javascript中工作的RegEx在PHP中不会这样做

I will try to make my question short yet understandable, I have a simple RegEx I use in javascript to check for characters that aren't alphanumeric (AKA Symbols). It would be "/[$-/:-?{-~!"^_`[]]/"

In javascript, doing

if(/[$-/:-?{-~!"^_`\[\]]/.test( string ))

just works, if any of those characters are in the string, it will give true, else, it will give false. I tried to do the same in PHP, the following way

if(preg_match('/[$-/:-?{-~!"^_`\[\]]/', $string ))

other regexes work when done this way, but this particular one simply will give false no matter what when ran in PHP.

Is there any reason to this? Am I doing something wrong? Does PHP comprehend regexes in a different way? What should I change to make it work?

Thanks for your time.

  • 写回答

1条回答 默认 最新

  • dongyuan9892 2017-06-09 21:20
    关注

    Since php uses PCRE, you will get a pattern error using delimiter / as seen here http://regex101.com/r/3ILGgE/1

    So, it should be escaped correctly.

    Using / as the delimiter, the string is

    '/[$-\/:-?{-~!"^_`\[\]]/'  
    

    Using ~ as the delimiter, the string is

    '~[$-/:-?{-\~!"^_`\[\]]~'  
    

    Also, be aware you have a couple of range's in the class $-/ and :-? and {-~
    that will include the characters between the from/to range characters as well
    and does not include the range character - itself as it is an operator.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程