【问题标题】:understanding the following regex理解以下正则表达式
【发布时间】:2010-08-26 08:14:35
【问题描述】:

我写了一个正则表达式,但它没有像我预期的那样工作。请看一下


preg_match_all("/([\.\:]?)(.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})/siu",$content,$matched);

[^\s]*".preg_quote($word)."[^\s]//

这部分匹配整个单词,如果它包含关键字,例如如果我搜索 wor 关键字,它匹配 keyword

.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65}

在这里,我在关键字之前和之后最多可以看到 65 个字符,即。我会得到的

这里有很多词关键字和这里的其他词


现在,有什么问题。如果 {65} 个字符内有任何 [.:] 字符,我会尝试从开头匹配句子

如果我有 sach 结构 - word1 word2 . {这里少于 65 个字符} 关键字 {这里有其他字符}

我期待,那么如果我写了([\.\:]?)(.{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})

它将匹配.{less then 65 character here} keyword {65 characters}

但事实并非如此。 [\.\:]? 部分对正则表达式没有任何影响。它匹配所有 {65} 个字符。

如果句首在关键字前65个字符以内,我需要从开头匹配句子

【问题讨论】:

    标签: php regex


    【解决方案1】:

    [.:]? 表示“匹配一个点 (.)、一个冒号 (:),或者什么都不匹配”;如果下一个字符不是点或冒号,([.:]?) 不匹配。然后.{0,65} 最多匹配 65 个,包括.:。我想这就是你要找的:

    $source='A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids.';
    $word = 'regular';
    preg_match_all('#[^.:]{0,65}\b'.preg_quote($word).'\b.{0,65}#siu', $source, $matches);
    print_r($matches);
    

    输出:

    Array
    (
      [0] => Array
        (
          [0] => A regular expression (regex or regexp for short) is a special text string 
          [1] =>  You can think of regular expressions as wildcards on steroids.
        )
    
    )
    

    (在Ideone 上观看直播)

    【讨论】:

      【解决方案2】:

      只需更换拳头

      .{0,65}
      

      [^\.\:]{0,65}
      

      毕竟,它可能看起来像

      preg_match_all("/([^\.\:]{0,65}?[^\s]*".preg_quote($word)."[^\s]*.{0,65})/siu",$content,$matched);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-17
        • 2017-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多