PHP:如何获取preg_match_all的字符串索引?

atp*_*atp 6 php regex preg-match-all

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

/eat (apple|pear)/
/I like/
Run Code Online (Sandbox Code Playgroud)

和文字

"I like to eat apples on a rainy day, but on sunny days, I like to eat pears."
Run Code Online (Sandbox Code Playgroud)

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

match: 0,5 (I like)
match: 10,19 (eat apples)
match: 57,62 (I like)
match: 67,75 (eat pears)
Run Code Online (Sandbox Code Playgroud)

有没有办法使用preg_match_all获取这些索引,而不是每次循环文本?

编辑:解决方案 PREG_OFFSET_CAPTURE!

gho*_*g74 18

您可以尝试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);
Run Code Online (Sandbox Code Playgroud)

产量

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

    [1] => Array
        (
            [0] => apple
            [1] => 14
        )

)
Run Code Online (Sandbox Code Playgroud)

  • 也适用于 preg_match_all() :D (2认同)