I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE):
http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/
CXVI. Expressions rationnelles compatibles Perl
Introduction
La syntaxe des masques utilisés dans ces fonctions ressemble fort à celle de Perl. Les expressions seront entourées de délimiteurs, slash (/), par exemple. N'importe quel caractère peut servir de délimiteur, tant qu'il n'est pas alpha-numérique ou n'est pas un anti-slash (\). Si un délimiteur doit être utilisé dans l'expression, il faudra l'échapper avec un anti-slash. Depuis PHP 4.0.4, vous pouvez utiliser les délimiteurs (), {}, [], et <>, comme en Perl. Voir la syntaxe des masques pour plus d'explications.
Le délimiteur final peut être suivi d'options qui affecteront la recherche. Voir aussi options de recherche.
PHP supporte également les expressions rationnelles utilisant la syntaxe POSIX étendue (fonctions REGEX POSIX-extended).
Note : Cette extension maintient un cache global par thread des expressions rationnelles compilées (jusqu'à 4096).
| Avertissement |
Vous devez être conscient des limitations de PCRE. Lisez http://www.pcre.org/pcre.txt pour plus de détails. |
Pré-requis
Ces fonctions sont disponibles dans le module PHP standard, qui est toujours accessible.
Installation
À partir de PHP 4.2.0, ces fonctions sont activées par défaut. Pour les anciennes versions, vous devez configurer et compiler PHP avec l'option --with-pcre-regex afin de pouvoir les utiliser. Utilisez --with-pcre-regex=DIR pour spécifier le répertoire où la bibliothèque PCRE est installée si vous n'utilisez pas la bibliothèque incluse dans PHP. Pour les versions plus anciennes de PHP, vous devez configurer et compiler PHP avec --with-pcre-regex[=DIR] pour pouvoir utiliser ces fonctions.
La version Windows de PHP dispose du support automatique de cette extension. Vous n'avez pas à ajouter de bibliothèque supplémentaire pour disposer de ces fonctions.
Configuration à l'exécution
Le comportement de ces fonctions est affecté par la configuration dans le fichier php.ini.
Tableau 1. Options de configuration PCRE
| Nom | Défaut | Modifiable | Changelog |
|---|---|---|---|
| pcre.backtrack_limit | 100000 | PHP_INI_ALL | Disponible depuis PHP 5.2.0. |
| pcre.recursion_limit | 100000 | PHP_INI_ALL | Disponible depuis PHP 5.2.0. |
Voici un éclaircissement sur l'utilisation des directives de configuration.
- pcre.backtrack_limit entier
PCRE's backtracking limit.
- pcre.recursion_limit entier
Limite de récursivité PCRE. Notez que si vous définissez cette valeur à un nombre élevé, vous devriez consommer tous les processus disponibles et, éventuellement, faire crasher PHP (la taille limite de la pile imposée par le système sera atteinte).
Types de ressources
Cette extension ne définit aucune ressource.
Constantes pré-définies
Ces constantes sont définies par cette extension, et ne sont disponibles que si cette extension a été compilée avec PHP, ou bien chargée au moment de l'exécution.
Tableau 2. Constantes PREG
| Constante | Description |
|---|---|
| PREG_PATTERN_ORDER | Ordonne les résultats de façon à ce que $matches[0] contienne les résultats qui correspondent au masque entier, $matches[1] ceux qui correspondent à la première parenthèse capturante, $matches[2] ceux qui correspondent à la deuxième parenthèse capturante, etc. Cette constante est utilisée avec preg_match_all(). |
| PREG_SET_ORDER | Les résultats sont classés de telle façon que $matches[0] contient la première série de résultat, $matches[1] la deuxième, etc. Cette constante est utilisée avec preg_match_all(). |
| PREG_OFFSET_CAPTURE | Voir la description de PREG_SPLIT_OFFSET_CAPTURE. Cette constante est utilisée depuis PHP 4.3.0 . |
| PREG_SPLIT_NO_EMPTY | Si cette option est activée, seules les sous-chaînes non vides seront retournées par preg_split(). |
| PREG_SPLIT_DELIM_CAPTURE | Si cette option est activée, les expressions entre parenthèses entre les délimiteurs de masques seront aussi capturées et retournées. Cette option a été ajoutée en PHP 4.0.5. Cette constante est utilisée avec preg_split(). |
| PREG_SPLIT_OFFSET_CAPTURE | Si cette constante est utilisée avec preg_split(), l'offset de début de résultat sera retourné, en plus de la chaîne résultat. Notez que cela change la nature du résultat retourné en un tableau contenant une chaîne à l'offset 0 et une chaîne contenant un offset à l'offset 1. Cette option est disponible depuis PHP 4.3.0. |
| PREG_NO_ERROR | Retourné par la fonction preg_last_error() s'il n'y a pas d'erreur. Disponible depuis PHP 5.2.0. |
| PREG_INTERNAL_ERROR | Retourné par la fonction preg_last_error() s'il y a une erreur interne PCRE. Disponible depuis PHP 5.2.0. |
| PREG_BACKTRACK_LIMIT_ERROR | Retourné par la fonction preg_last_error() si backtrack limit a été atteint. Disponible depuis PHP 5.2.0. |
| PREG_RECURSION_LIMIT_ERROR | Retourné par la fonction preg_last_error() si recursion limit a été atteint. Disponible depuis PHP 5.2.0. |
| PREG_BAD_UTF8_ERROR | Retourné par la fonction preg_last_error() si la dernière erreur est du à une malformation des données UTF-8 (uniquement lors de l'exécution d'une regex en mode UTF-8). Disponible depuis PHP 5.2.0. |
- Table des matières
- options de recherche -- Options disponibles pour les expressions rationnelles
- syntaxe des masques -- Fonctionnement des expressions rationnelles
- preg_grep -- Retourne un tableau avec les résultats de la recherche
- preg_last_error -- Retourne le code erreur de la dernière regex PCRE exécutée
- preg_match_all -- Expression rationnelle globale
- preg_match -- Expression rationnelle standard
- preg_quote -- Echappement des caractères spéciaux des expressions rationnelles
- preg_replace_callback -- Rechercher/remplacer avec une expression rationnelle et fonction de callback
- preg_replace -- Rechercher et remplacer par expression rationnelle standard
- preg_split -- Eclate une chaîne par expression rationnelle
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 :-)
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
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.
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');
?>
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)
Regular Expressions Tutorial from non PHP sites
http://www.amk.ca/python/howto/regex/
http://sitescooper.org/tao_regexps.html
http://www.english.uga.edu/humcomp/perl/regex2a.html
http://www.english.uga.edu/humcomp/perl/regexps.html
http://www.english.uga.edu/humcomp/perl/regular_expressions.HTML
http://www.english.uga.edu/humcomp/perl/
http://java.sun.com/docs/books/tutorial/extra/regex/
http://gnosis.cx/publish/programming/regular_expressions.html
http://www.zvon.org/other/PerlTutorial/Books/Book1/
http://it.metr.ou.edu/regex/
http://www.regular-expressions.info/
