Função PHP preg_filter()
Exemplo
Envolva os números entre colchetes em uma lista de strings:
<?php
$input = [
"It is 5 o'clock",
"40 days",
"No
numbers here",
"In the year 2000"
];
$result =
preg_filter('/[0-9]+/', '($0)', $input);
print_r($result);
?>
Definição e uso
A preg_filter()
função retorna uma string ou array de strings em que as correspondências do padrão foram substituídas pela string de substituição.
Se a entrada for um array, esta função retornará um array. Se a entrada for uma string, essa função retornará uma string.
Esta função é semelhante preg_replace()
com uma diferença: quando uma correspondência para o padrão não for encontrada em uma string de entrada, a string não será usada no valor de retorno. Nesse cenário, se a entrada for uma string em vez de uma matriz, a função retornará null .
Strings de substituição podem conter referências anteriores na forma \n ou $n onde n é o índice de um grupo no padrão. Na string retornada, as instâncias de \n e $n serão substituídas pela substring que foi correspondida pelo grupo ou, se \0 ou $0 forem usados, pela expressão inteira.
Sintaxe
preg_filter(pattern, replacement, input, limit, count)
Valores de parâmetro
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
replacement | Required. A string which will replace the matched patterns. It may contain backreferences |
input | Required. A string or array of strings in which the 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 matriz de strings substituídas se a entrada for uma matriz, uma string com substituições feitas se a entrada for uma string ou null se a entrada for uma string e nenhuma correspondência foi encontrada |
---|---|
Versão do PHP: | 5.3.0 |
❮ Referência PHP RegExp