PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Modificadores de Patrón> <pcntl_wtermsig
Last updated: Tue, 27 Nov 2007

view this page in

Funciones de Expresiones Regulares (Compatibles con Perl)

Introducción

La sintaxis para los patrones usados en estas funciones se asemeja considerablemente con la sintaxis de Perl. La expresión debe estar rodeada por delimitadores, una barra acostada (/), por ejemplo. Cualquier caracter puede ser usado como delimitador siempre y cuando no sea alfanumérico ni la barra invertida (\). Si el caracter delimitador tiene que ser usado en la expresión misma, necesita ser escapado por la barra invertida. A partir de PHP 4.0.4, puede usar también los delimitadores de coincidencia tipo Perl (), {}, [], y <>. Vea Sintaxis de los Patrones para una explicación detallada.

El delimitador de cierre puede estar seguido de varios modificadores que afectan las coincidencias. Vea Modificadores de Patrón.

PHP soporta también expresiones regulares usando una sintaxis POSIX-extendida, por medio de las funciones regex POSIX-extendidas.

Note: Esta extensión mantiene un caché global por-hilo de expresiones regulares compiladas (hasta un máximo de 4096).

Warning

Es importante que conozca sobre las limitaciones de PCRE. Lea » http://www.pcre.org/pcre.txt para más información.

Requisitos

No se necesitan bibliotecas externas para construir esta extensión

Instalación

A partir de PHP 4.2.0, estas funciones están habilitadas por defecto. Puede deshabilitar las funciones pcre con --without-pcre-regex. Use --with-pcre-regex=DIR para especificar la ubicación de los archivos de inclusión y bibliotecas de PCRE, si no desea usar la biblioteca incluida. En versiones más antiguas, usted tendrá que configurar y compilar PHP con --with-pcre-regex[=DIR] para poder hacer uso de estas funciones.

La versión para Windows de PHP tiene soporte nativo para esta extensión. No se necesita cargar ninguna extensión adicional para usar estas funciones.

Configuración en tiempo de ejecución

El comportamiento de estas funciones está afectado por los valores definidos en php.ini.

PCRE Configuration Options
Name Default Changeable Changelog
pcre.backtrack_limit "100000" PHP_INI_ALL Available since PHP 5.2.0.
pcre.recursion_limit "100000" PHP_INI_ALL Available since PHP 5.2.0.
For further details and definitions of the PHP_INI_* constants, see the Directivas de php.ini.

A continuación se presenta una corta explicación de las directivas de configuración.

pcre.backtrack_limit integer

PCRE's backtracking limit.

pcre.recursion_limit integer

PCRE's recursion limit. Please note that if you set this value to a high number you may consume all the available process stack and eventually crash PHP (due to reaching the stack size limit imposed by the Operating System).

Tipos de recursos

Esta extensión no tiene ningún tipo de recurso definido.

Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.

constantes PREG
constante descripción
PREG_PATTERN_ORDER Ordena los resultados de modo que $coincidencias[0] sea una matriz de coincidencias del patrón completo, $coincidencias[1] sea una matriz de cadenas que coincidieron con el primer subpatrón entre paréntesis, y así sucesivamente. Esta bandera sólo es usada con preg_match_all().
PREG_SET_ORDER Ordena los resultados de modo que $coincidencias[0] resulte ser una matriz del primer conjunto de coincidencias, $matches[1] sea una matriz del segundo conjunto de coincidencias, y así sucesivamente. Esta bandera únicamente es usada con preg_match_all().
PREG_OFFSET_CAPTURE Consulte la descripción de PREG_SPLIT_OFFSET_CAPTURE. Esta bandera está disponible desde PHP 4.3.0.
PREG_SPLIT_NO_EMPTY Esta bandera le dice a preg_split() que devuelva únicamente resultados que no sean vacíos.
PREG_SPLIT_DELIM_CAPTURE Esta bandera le indica a preg_split() que capture las expresiones entre paréntesis dentro del patrón de delimitación también. Esta bandera está disponible desde PHP 4.0.5.
PREG_SPLIT_OFFSET_CAPTURE Si esta bandera está activa, la posición de desplazamiento correspondiente a cada coincidencia será devuelta también. Note que esto modifica el valor devuelto a una matriz en la que cada elemento es también una matriz que consiste de la cadena coincidente en el subíndice 0 y su posición de desplazamiento al interior de la cadena de asunto en el subíndice 1. Esta bandera está disponible a partir de PHP 4.3.0 y sólo es usada por preg_split().
PREG_NO_ERROR Devuelta por preg_last_error() si no ocurrieron errores. Disponible desde PHP 5.2.0.
PREG_INTERNAL_ERROR Devuelta por preg_last_error() si hubo un error interno de PCRE. Disponible desde PHP 5.2.0.
PREG_BACKTRACK_LIMIT_ERROR Devuelta por preg_last_error() si el límite de referencias hacia atrás fue consumido. Disponible desde PHP 5.2.0.
PREG_RECURSION_LIMIT_ERROR Devuelta por preg_last_error() si el límite de recursión fue consumido. Disponible desde PHP 5.2.0.
PREG_BAD_UTF8_ERROR Devuelta por preg_last_error() si el último error fue causado por datos UTF-8 inválidos (solo cuando se ejecuta una expresión regular en modo UTF-8). Disponible desde PHP 5.2.0.
PCRE_VERSION Versión y fecha de lanzamiento de PCRE (p.ej. "7.0 18-Dec-2006"). Disponible desde PHP 5.2.4.

Ejemplos

Example#1 Ejemplos de patrones válidos

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Example#2 Ejemplos de patrones inválidos

  • /href='(.*)' - carece de delimitador de cierre
  • /\w+\s*\w+/J - modificador 'J' desconocido
  • 1-\d3-\d3-\d4| - carece del delimitador de apertura

Table of Contents

  • Modificadores de Patrón — Describe los posibles modificadores en patrones de expresiones regulares
  • Sintaxis de los Patrones — Describe la sintaxis de expresiones regulares PCRE
  • preg_grep — Devolver una matriz con las entradas que coinciden con el patrón
  • preg_last_error — Returns the error code of the last PCRE regex execution
  • preg_match_all — Realizar una comparación global con una expresión regular
  • preg_match — Realizar una comparación de expresión regular
  • preg_quote — Escapar caracteres de expresiones regulares
  • preg_replace_callback — Realizar una búsqueda con expresiones regulares y generar reemplazos usando una llamada de retorno
  • preg_replace — Realizar una operación de búsqueda y reemplazo con expresiones regulares
  • preg_split — Separar una cadena por una expresión regular


Modificadores de Patrón> <pcntl_wtermsig
Last updated: Tue, 27 Nov 2007
 
add a note add a note User Contributed Notes
PCRE
stronk7 at moodle dot org
13-Sep-2007 11:42
One comment about 5.2.x and the pcre.backtrack_limit:

Note that this setting wasn't present under previous PHP releases and the behaviour (or limit) under those releases was, in practise,  higher so all these PCRE functions were able to "capture" longer strings.

With the arrival of the setting, defaulting to 100000 (less than 100K), you won't be able to match/capture strings over that size using, for example "ungreedy" modifiers.

So, in a lot of situations, you'll need to raise that (very small IMO) limit.

The worst part is that PHP simply won't match/capture those strings over pcre.backtrack_limit and will it be 100% silent about that (I think that throwing some NOTICE/WARNING if raised could help a lot to developers).

There is a lot of people suffering this changed behaviour from I've read on forums, bugs and so on).

Hope this note helps, ciao :-)
tabac (at) uu (dot) dk
27-Jul-2007 04:19
Hello bermi

<?php
 
if(preg_match("/((a+)?)+/", "a")){
    echo
"Matched";
  }
?>

Segfault is always bad, but realize what you are asking here:

"Is there one or more occurrences of zero or one sequences of one or more 'a' ?"

Considering the backtracking algorithm used, the RE engine must consider if an infinite sequence of sub matches of which all but one has a length of zero.

This is a bug, but it is in line with the famous "ls -l /usr/../*/../*/../*/../*/../*" bug
misc at e2007 dot cynergi dot com
05-May-2007 02:16
PCRE faster than POSIX RE? Not always.

In a recent search-engine project here at Cynergi, I had a simple loop with a few cute ereg_replace() functions that took 3min to process data. I changed that 10-line loop into a 100-line hand-written code for replacement and the loop now took 10s to process the same data! This opened my eye to what can *IN SOME CASES* be very slow regular expressions.

Lately I decided to look into Perl-compatible regular expressions (PCRE). Most pages claim PCRE are faster than POSIX, but a few claim otherwise. I decided on bechmarks of my own.

My first few tests confirmed PCRE to be faster, but... the results were slightly different than others were getting, so I decided to benchmark every case of RE usage I had on a 8000-line secure (and fast) Webmail project here at Cynergi to check it out.

The results? Inconclusive! Sometimes PCRE *are* faster (sometimes by a factor greater than 100x faster!), but some other times POSIX RE are faster (by a factor of 2x).

I still have to find a rule on when are one or the other faster. It's not only about search data size, amount of data matched, or "RE compilation time" which would show when you repeated the function often: one would *always* be faster than the other. But I didn't find a pattern here. But truth be said, I also didn't take the time to look into the source code and analyse the problem.

I can give you some examples, though. The POSIX RE

([0-9]{4})/([0-9]{2})/([0-9]{2})[^0-9]+
([0-9]{2}):([0-9]{2}):([0-9]{2})

is 30% faster in POSIX than when converted to PCRE (even if you use \d and \D and non-greedy matching). On the other hand, a similarly PCRE complex pattern

/[0-9]{1,2}[ \t]+[a-zA-Z]{3}[ \t]+[0-9]{4}[ \t]+[0-9]{1,2}:[0-9]{1,2}(:[0-9]{1,2})?[ \t]+[+-][0-9]{4}/

is 2.5x faster in PCRE than in POSIX RE. Simple replacement patterns like

ereg_replace( "[^a-zA-Z0-9-]+", "", $m );

are 2x faster in POSIX RE than PCRE. And then we get confused again because a POSIX RE pattern like

(^|\n|\r)begin-base64[ \t]+[0-7]{3,4}[ \t]+......

is 2x faster as POSIX RE, but the case-insensitive PCRE

/^Received[ \t]*:[ \t]*by[ \t]+([^ \t]+)[ \t]/i

is 30x faster than its POSIX RE version!

When it comes to case sensitivity, PCRE has so far seemed to be the best option. But I found some really strange behaviour from ereg/eregi. On a very simple POSIX RE

(^|\r|\n)mime-version[ \t]*:

I found eregi() taking 3.60s (just a number in a test benchmark), while the corresponding PCRE took 0.16s! But if I used ereg() (case-sensitive) the POSIX RE time went down to 0.08s! So I investigated further. I tried to make the POSIX RE case-insensitive itself. I got as far as this:

(^|\r|\n)[mM][iI][mM][eE]-vers[iI][oO][nN][ \t]*:

This version also took 0.08s. But if I try to apply the same rule to any of the 'v', 'e', 'r' or 's' letters that are not changed, the time is back to the 3.60s mark, and not gradually, but immediatelly so! The test data didn't have any "vers" in it, other "mime" words in it or any "ion" that might be confusing the POSIX parser, so I'm at a loss.

Bottom line: always benchmark your PCRE / POSIX RE to find the fastest!

Tests were performed with PHP 5.1.2 under Windows, from the command line.

Pedro Freire
cynergi.com
nickspring at mail dot ru
14-Oct-2006 04:47
Regular Expressions Tutorial on russian language is accessible on http://www.pcre.ru
lgandras at hotmail dot com
20-Feb-2006 12:19
I read this part, but i couldn't undertand a single word beacause before i must know Basic regular expression. Somebody put a link for PERL that is almost like PHP but here is one totally dedicated to PHP:

http://weblogtoolscollection.com/regex/regex.php
Gokul
06-Feb-2006 10:59
I came accross this nice tutorial for regural expression in perl
http://perldoc.perl.org/perlretut.html
richardh at phpguru dot org
22-Sep-2005 09:50
There's a printable PDF PCRE cheat sheet available here:

http://www.phpguru.org/article.php?ne_id=67

Has the common metacharacters, quantifiers, pattern modifiers, character classes and assertions with short explanations.
hfuecks at nospam dot org
04-Jul-2005 12:21
Good PCRE tutorial at http://www.tote-taste.de/X-Project/regex/ - well explained but still in depth
Ned Baldessin
24-Oct-2004 03:08
If you want to perform regular expressions on Unicode strings, the PCRE functions will NOT be of any help. You need to use the Multibyte extension : mb_ereg(), mb_eregi(), pb_ereg_replace() and so on. When doing so, be carefull to set the default text encoding to the same encoding used by the text you are searching and replacing in. You can do that with the mb_regex_encoding() function. You will probably also want to set the default encoding for the other mb_* string functions with mb_internal_encoding().

So when dealing with, say, french text, I start with these :
<?php
mb_internal_encoding
('UTF-8');
mb_regex_encoding('UTF-8');
setlocale(LC_ALL, 'fr-fr');
?>
steve at stevedix dot de
20-Jul-2004 03:17
Something to bear in mind is that regex is actually a declarative programming language like prolog : your regex is a set of rules which the regex interpreter tries to match against a string.   During this matching, the interpreter will assume certain things, and continue assuming them until it comes up against a failure to match, which then causes it to backtrack.  Regex assumes "greedy matching" unless explicitly told not to, which can cause a lot of backtracking.  A general rule of thumb is that the more backtracking, the slower the matching process.

It is therefore vital, if you are trying to optimise your program to run quickly (and if you can't do without regex), to optimise your regexes to match quickly.

I recommend the use of a tool such as "The Regex Coach" to debug your regex strings.

http://weitz.de/files/regex-coach.exe (Windows installer) http://weitz.de/files/regex-coach.tgz (Linux tar archive)
hrz at geodata dot soton dot ac dot uk
06-Mar-2002 09:33
If you're venturing into new regular expression territory with a lack of useful examples then it would pay to get familiar with this page:

http://www.pcre.org/man.txt

Modificadores de Patrón> <pcntl_wtermsig
Last updated: Tue, 27 Nov 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites