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

后端 未结 2 874
北海茫月
北海茫月 2020-12-19 02:14

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          


        
2条回答
  •  情话喂你
    2020-12-19 02:47

    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
            )
    
    )
    

提交回复
热议问题