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

本小妞迷上赌 提交于 2019-12-10 04:37:10

问题


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 !


回答1:


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
        )

)



回答2:


Please keep in mind that if you use preg_match, and a group isn't matched then not an array will be returned, but an empty string. You can use T-Regx and use cleaner API:

$o = pattern('eat (apple|pear)')->match($text)->offsets()->all();
$o // [10, 14]

Or if you want some more advanced matches

pattern('eat (apple|pear)')
  ->match($text)
  ->iterate(function (Match $m) {
      $m->text();   // your fruit here
      $m->offset(); // your offset here
  });


来源:https://stackoverflow.com/questions/2451915/php-how-do-i-get-the-string-indexes-of-a-preg-match-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!