【问题标题】:preg_match match all starting wordspreg_match 匹配所有起始词
【发布时间】:2013-03-11 21:52:22
【问题描述】:

我正在尝试从单词列表中获取所有匹配的模式;

$pattern = '/^(ab|abc|abcd|asdf)/';
preg_match_all($pattern, 'abcdefgh', $matches);

我想得到'ab、abc和abcd'

但这只会返回“ab”。如果我在爆炸后循环遍历模式,它会起作用。

有没有办法通过单场比赛解决?

【问题讨论】:

    标签: php regex preg-match preg-match-all


    【解决方案1】:

    正则表达式在通过字符串进行匹配时会消耗字符,因此它们本身无法找到重叠的匹配项。

    您可以将前瞻断言等扩展功能与捕获组一起使用,但这需要一个丑陋的结构:

    preg_match_all(
        '/^
        (?:(?=(ab)))?
        (?:(?=(abc)))?
        (?:(?=(abcd)))?
        (?:(?=(asdf)))?
        /x', 
        $subject, $result, PREG_SET_ORDER);
    for ($matchi = 0; $matchi < count($result); $matchi++) {
        for ($backrefi = 0; $backrefi < count($result[$matchi]); $backrefi++) {
            # Matched text = $result[$matchi][$backrefi];
        } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 2018-08-25
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 1970-01-01
      相关资源
      最近更新 更多