Función PHP preg_match_all()
Ejemplo
Encuentra todas las apariciones de "ain" en una cadena:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern =
"/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
Definición y uso
La preg_match_all()
función devuelve el número de coincidencias de un patrón que se encontraron en una cadena y completa una variable con las coincidencias que se encontraron.
Sintaxis
preg_match_all(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. 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 |
Detalles técnicos
Valor devuelto: | Devuelve el número de coincidencias encontradas o 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.4: el parámetro de coincidencias se volvió opcional 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 el (? 'nombre' ) y (? <nombre>) sintaxis además de la anterior (?P<nombre>) |
Más ejemplos
Ejemplo
Utilice PREG_PATTERN_ORDER para establecer la estructura de la matriz de coincidencias . En este ejemplo, cada elemento de la matriz de coincidencias tiene todas las coincidencias para una de las agrupaciones de la expresión regular.
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern,
$str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
❮ Referencia PHP RegExp