dtrgqjcd877528 2011-11-13 15:28
浏览 22
已采纳

preg_match for。 /或\在PHP中

I am trying to match . \ or / using preg_match in PHP.

I thought this would do it but it's matching all strings.

$string = '';
$chars = '/(\.|\\|\/)/';
if (preg_match($chars, $string) != 0) {
    echo 'Chars found.';
}
  • 写回答

5条回答 默认 最新

  • dryift6733 2011-11-13 15:43
    关注

    Argument given to preg_match() is string. Strings are automatically escaped by PHP. For example, if you have {\\\\} (backslash) given to the regexp engine, PHP will first parse it creating {\\} (\\ is replaced by \).

    Next, regexp engine parses the regexp. It sees {\\} which PHP gave to regexp engine. It sees \ as escape character, so it actually matches \ character which was escaped by \.

    In your case, it looks like /(\.|\\|\/)/. PHP gives to regexp engine /(\.|\|\/)/ which is actually either . or |/ (notice that | character was escaped).

    Personally, I try to avoid escaping meta-characters, especially with how regexp engine works. I usually use [.] instead, it's more readable. Your regexp written with this would look like /([.]|\\\\|[/])/.

    It's possible to do few optimizations. While it's my personal thing, I prefer to use {} as delimiters (yes, you can use pairs of characters). Also, your regexp matches single characters, so you could easily write it as {[.\\\\/]}, which is very readable in my opinion (notice four slashes, it's needed because both PHP and regexp engine parse backslashes).

    Also, preg_match() returns number of matches. It will be always bigger than 0, so you can easily consider it to be boolean and avoid writting == 0. Instead, you can insert ! before string to make it negative. But I think you accidentally reversed condition (it matches if it doesn't match). Valid code below:

    $string = '';
    $chars = '{[.\\\\/]}';
    if (preg_match($chars, $string)) {
        echo 'Chars found.';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致