PHP: How to get preg_match_all string indexes?

let's say I have two regular expressions,

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

and text

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

I want to get the following indices with preg_match:

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

Is there a way to get these indexes using preg_match_all without looping through the text every time?

EDIT: SOLUTION PREG_OFFSET_CAPTURE!

+6
php regex preg-match-all
source share
1 answer

You can try the PREG_OFFSET_CAPTURE flag for 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); 

Exit

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

All Articles