Função PHP preg_replace_callback()
Exemplo
Contar letras em todas as palavras em uma frase:
<?php
function countLetters($matches) {
return $matches[0] . '(' .
strlen($matches[0]) . ')';
}
$input = "Welcome to W3Schools.com!";
$pattern = '/[a-z0-9\.]+/i';
$result = preg_replace_callback($pattern,
'countLetters', $input);
echo $result;
?>
Definição e uso
A preg_replace_callback()
função, dada uma expressão e um retorno de chamada, retorna uma string onde todas as correspondências da expressão são substituídas pela substring retornada pela função de retorno de chamada.
Sintaxe
preg_replace_callback(pattern, callback, input, limit, count)
Valores de parâmetro
Parameter | Description |
---|---|
pattern | Required. A regular expression or array of regular expressions indicating what to search for |
replacements | Required. A callback function which returns the replacement. The callback function has one parameter containing 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 |
Detalhes técnicos
Valor de retorno: | Retorna uma string ou uma matriz de strings resultante da aplicação das substituições à string ou strings de entrada. |
---|---|
Versão do PHP: | 4.0.5+ |
Registro de alterações: | PHP 5.1.0 - O parâmetro count foi adicionado |
❮ Referência PHP RegExp