Función PHP preg_match()
Ejemplo
Utilice una expresión regular para realizar una búsqueda sin distinción entre mayúsculas y minúsculas de "w3schools" en una cadena:
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo
preg_match($pattern, $str);
?>
Definición y uso
La preg_match()
función devuelve si se encontró una coincidencia en una cadena.
Sintaxis
preg_match(pattern, input, matches, flags, offset)
Valores paramétricos
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 |
Detalles técnicos
Valor devuelto: | Devuelve 1 si se encontró una coincidencia, 0 si no se encontraron coincidencias y falso si se produjo un error |
---|---|
Versión PHP: | 4+ |
Registro de cambios: | PHP 7.2: se agregó el indicador PREG_UNMATCHED_AS_NULL PHP 5.3.6: la función devuelve falso cuando el desplazamiento es más largo que la longitud de la entrada PHP 5.2.2: los subpatrones con nombre pueden usar (? 'nombre') y (? <nombre>) sintaxis adicional a la anterior (?P<nombre>) |
Más ejemplos
Ejemplo
Use PREG_OFFSET_CAPTURE para encontrar la posición en la cadena de entrada en la que se encontraron las coincidencias:
<?php
$str = "Welcome to W3Schools";
$pattern = "/w3schools/i";
preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
❮ Referencia PHP RegExp