[英]PHP: How do I get the string indexes of a preg_match_all?
假設我有兩個正則表達式,
/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!
您可以為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
)
)
請記住,如果使用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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.