Função PHP preg_match()
Exemplo
Use uma expressão regular para fazer uma pesquisa sem distinção entre maiúsculas e minúsculas por "w3schools" em uma string:
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo
preg_match($pattern, $str);
?>
Definição e uso
A preg_match()
função retorna se uma correspondência foi encontrada em uma string.
Sintaxe
preg_match(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:
|
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 1 se uma correspondência foi encontrada, 0 se nenhuma correspondência foi encontrada e 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.3.6 - A função retorna false quando o deslocamento é maior que o comprimento da entrada PHP 5.2.2 - Subpadrões nomeados podem usar o (?'nome') e (? <nome>) sintaxe além da anterior (?P<nome>) |
Mais exemplos
Exemplo
Use PREG_OFFSET_CAPTURE para encontrar a posição na string de entrada em que as correspondências foram encontradas:
<?php
$str = "Welcome to W3Schools";
$pattern = "/w3schools/i";
preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
❮ Referência PHP RegExp