Função PHP preg_match_all()
Exemplo
Encontre todas as ocorrências de "ain" em uma string:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern =
"/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
Definição e uso
A preg_match_all()
função retorna o número de correspondências de um padrão que foram encontradas em uma string e preenche uma variável com as correspondências encontradas.
Sintaxe
preg_match_all(pattern, input, matches, flags, offset)
Valores de parâmetro
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
input | Required. The string in which the search will be performed |
matches | Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found |
flags | Optional. A set of options that change how the matches array is structured. One of the following structures may be selected:
|
offset | Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match() function will not find matches that occur before the position given in this parameter |
Detalhes técnicos
Valor de retorno: | Retorna o número de correspondências encontradas ou false se ocorreu um erro |
---|---|
Versão do PHP: | 4+ |
Registro de alterações: | PHP 7.2 - Adicionado o sinalizador PREG_UNMATCHED_AS_NULL PHP 5.4 - O parâmetro matches tornou-se opcional PHP 5.3.6 - A função retorna false quando o offset é maior que o comprimento da entrada PHP 5.2.2 - Subpatterns nomeados podem usar o (?'name' ) e (? <nome>) além da sintaxe anterior (?P<nome>) |
Mais exemplos
Exemplo
Use PREG_PATTERN_ORDER para definir a estrutura da matriz de correspondências . Neste exemplo, cada elemento na matriz de correspondências tem todas as correspondências de um dos agrupamentos da expressão regular.
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern,
$str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
❮ Referência PHP RegExp