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

/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!

最佳答案

您可以尝试 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
        )

)

关于PHP:如何获取preg_match_all的字符串索引?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2451915/

10-12 00:54