Come saltare la prima regex partita?
-
27-09-2019 - |
Domanda
Esiste un modo per saltare il primo match quando usando l'espressione regolare e php.
O c'è qualche modo di achieveing questo utilizzando str_replace.
Grazie
AGGIORNAMENTO Sto cercando di rimuovere tutte le occorrenze di una stringa in un'altra stringa, ma voglio mantenere la prima occorrenza e.g
$toRemove = 'test';
$string = 'This is a test string to test to removing the word test';
Output stringa sarebbe:
Questa è una stringa di test per prova per rimuovere la parola prova
Soluzione
Easy PHP modo:
<?php
$pattern = "/an/i";
$text = "banANA";
preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
preg_match($pattern, $text, $matches, 0, $matches[0][1]);
echo $matches[0];
?>
vi darà "UN".
AGGIORNAMENTO:Non sapevo che fosse una sostituzione.Prova questo:
<?php
$toRemove = 'test';
$string = 'This is a test string to test to removing the word test';
preg_match("/$toRemove/", $string, $matches, PREG_OFFSET_CAPTURE);
$newString = preg_replace("/$toRemove/", "", $string);
$newString = substr_replace($newString, $matches[0][0], $matches[0][1], 0);
echo $newString;
?>
Trovare la prima partita e ricordare dove si era, quindi, elimina tutto, quindi mettere tutto ciò che era al primo posto in.
Altri suggerimenti
preg_replace('/((?:^.*?\btest\b)?.*?)\btest\b/', '$1', $string);
L'idea è partita e di acquisire ciò che precede ogni partita, e plug-in. (?:^.*?test)?
cause l' prima istanza di test
per essere inclusi nell'acquisizione.(Tutti i \b
s evitare il parziale parola corrisponde, come il test
in smartest
o testify
.)
si supponga 'bla' è la tua espressione regolare, bla(bla) corrispondono e catturare il secondo
Ritardo di risposta, ma potrebbe essere utile per le persone.
$string = "This is a test string to test something with the word test and replacing test";
$replace = "test";
$tmp = explode($replace, $string);
$tmp[0] .= $replace;
$newString = implode('', $tmp);
echo $newString; // Output: This is a test string to something with the word and replacing