PHP: Come faccio ad avere gli indici stringa di un preg_match_all?
-
20-09-2019 - |
Domanda
diciamo che ho due espressioni regolari di,
/eat (apple|pear)/
/I like/
e il testo
"I like to eat apples on a rainy day, but on sunny days, I like to eat pears."
Quello che voglio è quello di ottenere i seguenti indici con preg_match:
match: 0,5 (I like)
match: 10,19 (eat apples)
match: 57,62 (I like)
match: 67,75 (eat pears)
C'è un modo per ottenere questi indici usando preg_match_all senza scorrendo il testo ogni volta?
EDIT: SOLUZIONE PREG_OFFSET_CAPTURE
Soluzione
Si può provare bandiera PREG_OFFSET_CAPTURE
per 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
)
)
Altri suggerimenti
Si prega di tenere presente che se si utilizza preg_match
, e un gruppo non corrisponde quindi una matrice non verrà restituito, ma una stringa vuota. È possibile utilizzare T-Regx e utilizzare API più pulito :
$o = pattern('eat (apple|pear)')->match($text)->offsets()->all();
$o // [10, 14]
O se volete alcune partite più avanzate
pattern('eat (apple|pear)')
->match($text)
->iterate(function (Match $m) {
$m->text(); // your fruit here
$m->offset(); // your offset here
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow