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 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持