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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。