duandi4238
2014-06-23 08:45 阅读 54
已采纳

需要匹配PHP正则表达式中的多个反斜杠

I'm trying to match 4 backslahes using preg_match.

preg_match('/\\\\\\\\/',$subject) works fine, but preg_match('/\\{4}/',$subject) doesn't.

Perhaps I'm using {} incorrectly. Could anyone advise?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    doumang20060820 doumang20060820 2014-06-23 09:00

    Ok I got it: Two backslashes mean you want one backslash in your string: So for the regex it looks like this: /\{4}/ Which means you want to escape the {

    What you need here is:

    preg_match('/\\\\{4}/', $subject);
    

    That looks for the regex like this: /\\{4}/ and works properly.

    点赞 评论 复制链接分享
  • douzhimao8656 douzhimao8656 2014-06-23 08:57

    Use this:

    preg_match('/(?:\\\\){2}/',$subject, $m);
    

    It matches 4 backslashes.

    点赞 评论 复制链接分享
  • dtv995719 dtv995719 2014-06-23 09:01

    Regex is the wrong tool when you're looking for a literal string.

    strpos($subject, str_repeat("\\",4)) !== false
    
    点赞 评论 复制链接分享

相关推荐