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

前端之家收集整理的这篇文章主要介绍了PHP:如何获取preg_match_all的字符串索引?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有两个正则表达式,
/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_match()的PREG_OFFSET_CAPTURE标志:
$subject="I like to eat apples on a rainy day,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相关文章