Tutorial PHP

PHP INÍCIO Introdução ao PHP Instalação do PHP Sintaxe PHP Comentários PHP Variáveis ​​PHP PHP Eco/Impressão Tipos de dados PHP Strings PHP Números PHP Matemática PHP Constantes PHP Operadores PHP PHP If...Else...Elseif Chave PHP Loops PHP Funções PHP Matrizes PHP PHP Superglobais PHP RegEx

Formulários PHP

Manipulação de formulários PHP Validação de formulário PHP Formulário PHP obrigatório URL/e-mail do formulário PHP Formulário PHP completo

PHP Avançado

Data e hora do PHP Incluir PHP Manipulação de arquivos PHP Arquivo PHP Abrir/Ler Arquivo PHP Criar/Gravar Upload de arquivo PHP Cookies PHP Sessões PHP Filtros PHP Filtros PHP Avançados Funções de retorno de chamada do PHP PHP JSON Exceções do PHP

PHP OOP

PHP O que é POO Classes/objetos PHP Construtor PHP Destruidor PHP Modificadores de acesso PHP Herança PHP Constantes PHP Classes abstratas PHP Interfaces PHP Características PHP Métodos estáticos PHP Propriedades estáticas do PHP Namespaces PHP Iteráveis ​​PHP

Banco de dados MySQL

Banco de dados MySQL MySQL Connect MySQL Criar banco de dados MySQL Criar Tabela Dados de inserção do MySQL MySQL Obter Último ID MySQL Inserir Múltiplo Preparado para MySQL Dados de seleção do MySQL MySQL Onde MySQL Ordenar por Dados de exclusão do MySQL Dados de atualização do MySQL Dados de limite do MySQL

PHP XML

Analisadores XML PHP Analisador PHP SimpleXML PHP SimpleXML - Obter PHP XML Expatriado PHP XML DOM

PHP - AJAX

Introdução AJAX PHP AJAX Banco de dados AJAX XML AJAX Pesquisa em tempo real AJAX Enquete AJAX

Exemplos PHP

Exemplos PHP Compilador PHP Teste PHP Exercícios PHP Certificado PHP

Referência PHP

Visão geral do PHP Matriz PHP Calendário PHP Data do PHP Diretório PHP Erro PHP Exceção PHP Sistema de arquivos PHP Filtro PHP PHP FTP PHP JSON Palavras-chave PHP PHP Libxml Correio PHP Matemática PHP PHP Diversos PHP MySQLi Rede PHP Controle de saída PHP PHP RegEx PHP SimpleXML Fluxo PHP String PHP Manipulação de variáveis ​​PHP Analisador XML PHP PHP Zip Fusos horários PHP

Função PHP preg_match()

❮ Referência PHP RegExp

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:
  • PREG_OFFSET_CAPTURE - When this option is enabled, each match, instead of being a string, will be an array where the first element is a substring containing the match and the second element is the position of the first character of the substring in the input.
  • PREG_UNMATCHED_AS_NULL - When this option is enabled, unmatched subpatterns will be returned as NULL instead of as an empty string.
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