PHP:如何获取preg_match_all的字符串索引? [英] PHP: How do I get the string indexes of a preg_match_all?

查看:128
本文介绍了PHP:如何获取preg_match_all的字符串索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个正则表达式,

let's say I have two regexp's,

/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获得以下索引:

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)

有什么方法可以使用preg_match_all来获取这些索引,而不必每次都遍历文本吗?

Is there any way to get these indexes using preg_match_all without looping through the text every single time?

解决方案 PREG_OFFSET_CAPTURE!

SOLUTION PREG_OFFSET_CAPTURE !

推荐答案

您可以尝试PREG_OFFSET_CAPTURE标志. rel ="noreferrer"> preg_match() :

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

输出

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

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

)

这篇关于PHP:如何获取preg_match_all的字符串索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆