PHP:如何获取 preg_match_all 的字符串索引?

发布于 2024-08-25 10:24:27 字数 450 浏览 6 评论 0原文

假设我有两个正则表达式

/eat (apple|pear)/
/I like/

和文本

"I like to eat apples on a rainy day, but on sunny days, I like to eat pears."

我想要的是使用 preg_match 获取以下索引:

match: 0,5 (I like)
match: 10,19 (eat apples)
match: 57,62 (I like)
match: 67,75 (eat pears)

有没有办法使用 preg_match_all 获取这些索引,而无需每次都循环遍历文本?

编辑:解决方案 PREG_OFFSET_CAPTURE!

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 !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

白云悠悠 2024-09-01 10:24:28

请记住,如果您使用 preg_match,并且组不匹配,则不会返回数组,而是返回空字符串。您可以使用 T-Regx 并使用更干净的 API :

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

或者如果你想要一些更高级的比赛

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

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
  });
鱼忆七猫命九 2024-09-01 10:24:27

您可以尝试 preg_match() 的 PREG_OFFSET_CAPTURE 标志

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

输出

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

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

)

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
        )

)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文