Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 !

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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
        )

)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...