PHP preg_replace_callback_array() Funzione
Esempio
Mostra quante lettere o cifre si trovano in ogni parola in una frase:
<?php
function countLetters($matches) {
return $matches[0] . '[' .
strlen($matches[0]) . 'letter]';
}
function countDigits($matches) {
return $matches[0] . '[' . strlen($matches[0]) . 'digit]';
}
$input
= "There are 365 days in a year.";
$patterns = [
'/\b[a-z]+\b/i' =>
'countLetters',
'/\b[0-9]+\b/' => 'countDigits'
];
$result =
preg_replace_callback_array($patterns, $input);
echo $result;
?>
Definizione e utilizzo
La preg_replace_callback_array()
funzione restituisce una stringa o una matrice di stringhe in cui le corrispondenze di un insieme di espressioni regolari vengono sostituite con il valore restituito di una funzione di callback.
Nota: per ogni stringa, la funzione valuta i modelli nell'ordine in cui sono stati forniti. Il risultato della valutazione del primo modello sulla stringa viene utilizzato come stringa di input per il secondo modello e così via. Questo può portare a comportamenti imprevisti.
Sintassi
preg_replace_callback_array(patterns, input, limit, count)
Valori dei parametri
Parameter | Description |
---|---|
pattern | Required. An associative array which associates regular
expression patterns to callback functions. The callback functions have one parameter which is an array of matches.The first element in the array contains the match for the whole expression while the remaining elements have matches for each of the groups in the expression. |
input | Required. The string or array of strings in which replacements are being performed |
limit | Optional. Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string |
count | Optional. After the function has executed, this variable will contain a number indicating how many replacements were performed |
Dettagli tecnici
Valore di ritorno: | Restituisce una stringa o una matrice di stringhe risultanti dall'applicazione delle sostituzioni alla stringa o alle stringhe di input |
---|---|
Versione PHP: | 7+ |
Altri esempi
Esempio
Questo esempio illustra gli effetti potenzialmente imprevisti dei modelli valutati in sequenza. Innanzitutto, la sostituzione di countLetters aggiunge "[4letter]" a "days" e, dopo che la sostituzione è stata eseguita, la sostituzione di countDigits trova il "4" in "4letter" e aggiunge "[1digit]" a quello:
<?php
function countLetters($matches) {
return $matches[0] . '[' .
strlen($matches[0]) . 'letter]';
}
function countDigits($matches) {
return $matches[0] . '[' . strlen($matches[0]) . 'digit]';
}
$input
= "365 days";
$patterns = [
'/[a-z]+/i' => 'countLetters',
'/[0-9]+/' => 'countDigits'
];
$result =
preg_replace_callback_array($patterns, $input);
echo $result;
?>
❮ Riferimento PHP RegExp