假设我有两个正则表达式,
/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 ) )