Tutorial PHP

PHP INICIO Introducción PHP Instalación de PHP Sintaxis PHP Comentarios PHP Variables PHP PHP Echo / Imprimir Tipos de datos PHP Cadenas PHP Números PHP Matemáticas PHP Constantes PHP Operadores PHP PHP Si... Más... Elseif Cambio de PHP Bucles de PHP Funciones PHP Matrices de PHP Superglobales de PHP PHP expresión regular

Formularios PHP

Manejo de formularios PHP Validación de formulario PHP Formulario PHP requerido Formulario PHP URL/Correo electrónico Formulario PHP completo

PHP Avanzado

Fecha y hora PHP PHP Incluir Manejo de archivos PHP Archivo PHP Abrir/Leer Archivo PHP Crear/Escribir Carga de archivos PHP Cookies PHP Sesiones PHP Filtros PHP Filtros PHP avanzados Funciones de devolución de llamada de PHP PHPJSON Excepciones de PHP

POO de PHP

PHP ¿Qué es la programación orientada a objetos? Clases PHP/Objetos Constructor PHP Destructor PHP Modificadores de acceso de PHP Herencia de PHP Constantes PHP Clases abstractas de PHP Interfaces PHP Características de PHP Métodos estáticos de PHP Propiedades estáticas de PHP Espacios de nombres de PHP Iterables de PHP

Base de datos MySQL

Base de datos MySQL Conexión MySQL MySQL Crear base de datos Crear tabla MySQL MySQL Insertar datos MySQL Obtener la última identificación MySQL Insertar Múltiples MySQL preparado Datos seleccionados de MySQL mysql donde MySQL Ordenar por MySQL Eliminar datos Datos de actualización de MySQL Límite de datos de MySQL

PHPXML _

Analizadores PHP XML Analizador PHP SimpleXML PHP SimpleXML - Obtener PHP XML Expatriados PHP XML DOM

PHP -AJAX

Introducción a AJAX AJAXPHP Base de datos AJAX XML AJAX Búsqueda en vivo de AJAX Encuesta AJAX

Ejemplos de PHP

Ejemplos de PHP Compilador PHP Cuestionario de PHP Ejercicios PHP Certificado PHP

Referencia PHP

Descripción general de PHP Matriz de PHP Calendario PHP Fecha PHP Directorio PHP Error PHP Excepción PHP Sistema de archivos PHP Filtro PHP PHPFTP PHPJSON Palabras clave PHP PHP Libxml Correo PHP Matemáticas PHP PHP misceláneo PHP MySQLi Red PHP Control de salida de PHP PHP expresión regular PHP SimpleXML flujo PHP Cadena PHP Manejo de variables de PHP Analizador PHP XML código postal de PHP Zonas horarias de PHP

Función PHP preg_match_all()

❮ Referencia PHP RegExp

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:
  • PREG_PATTERN_ORDER - Default. Each element in the matches array is an array of matches from the same grouping in the regular expression, with index 0 corresponding to matches of the whole expression and the remaining indices for subpattern matches.
  • PREG_SET_ORDER - Each element in the matches array contains matches of all groupings for one of the found matches in the string.
Any number of the following options may be applied:
  • 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

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