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

后端 未结 2 878
北海茫月
北海茫月 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:37

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

提交回复
热议问题