【问题标题】:PHP: How do I get the string indexes of a preg_match_all?PHP:如何获取 preg_match_all 的字符串索引?
【发布时间】:2011-01-27 22:59:34
【问题描述】:

假设我有两个正则表达式,

/eat (apple|pear)/
/I like/

和文字

"I like to eat apples on a rainy day, but on sunny days, I like to eat pears."

我想要的是使用 preg_match 获得以下索引:

match: 0,5 (I like)
match: 10,19 (eat apples)
match: 57,62 (I like)
match: 67,75 (eat pears)

有什么方法可以使用 preg_match_all 获取这些索引,而无需每次都循环遍历文本?

编辑:解决方案 PREG_OFFSET_CAPTURE !

【问题讨论】:

    标签: php regex preg-match-all


    【解决方案1】:

    你可以试试PREG_OFFSET_CAPTURE标志preg_match()

    $subject="I like to eat apples on a rainy day, but on sunny days, I like to eat pears.";
    $pattern = '/eat (apple|pear)/';
    preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE );
    print_r($matches);
    

    输出

    $ php test.php
    Array
    (
        [0] => Array
            (
                [0] => eat apple
                [1] => 10
            )
    
        [1] => Array
            (
                [0] => apple
                [1] => 14
            )
    
    )
    

    【讨论】:

    • 也适用于 preg_match_all() :D
    【解决方案2】:

    请记住,如果您使用preg_match,并且组不匹配,则不会返回数组,而是返回空字符串。您可以使用T-Regx 并使用更简洁的 API:

    $o = pattern('eat (apple|pear)')->match($text)->offsets()->all();
    $o // [10, 14]
    

    或者如果你想要一些更高级的匹配

    pattern('eat (apple|pear)')
      ->match($text)
      ->iterate(function (Match $m) {
          $m->text();   // your fruit here
          $m->offset(); // your offset here
      });
    

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 2021-12-05
      • 2014-12-02
      • 2011-01-25
      • 1970-01-01
      相关资源
      最近更新 更多