Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How do I get the string indexes of a preg_match_all?

let's say I have two regexp's,

/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."

What I want is to get the following indexes 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 any way to get these indexes using preg_match_all without looping through the text every single time?

EDIT: SOLUTION PREG_OFFSET_CAPTURE !

like image 393
atp Avatar asked Mar 16 '10 03:03

atp


People also ask

What does preg match return?

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .

What does Preg_match mean in PHP?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.

Which of the following call to Preg_match will return true?

The preg_match() function returns true if pattern matches otherwise, it returns false.

Which of the following is used by Preg_match?

PHP | preg_match() Function. This function searches string for pattern, returns true if pattern exists, otherwise returns false.


1 Answers

You can try 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);

Output

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

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

)
like image 180
ghostdog74 Avatar answered Jan 05 '23 05:01

ghostdog74