@zooly:
And what if $myvar = 'te\\E.t'? It will match, when it shouldn't. That's why you should use preg_quote().
preg_quote
(PHP 4, PHP 5)
preg_quote — Escapar caracteres en una expresión regular
Descripción
preg_quote() toma string y pone una barra invertida delante de cada carácter que es parte de la sintaxis de la expresión regular. Esto es útil si tiene una cadena en tiempo de ejecución que necesite comparar con algún texto, y la cadena pueda contener caracteres de expresiones regulares especiales.
Los caracteres de expresiones regulares especiales son: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
Parámetros
- string
-
La cadena de entrada.
- delimiter
-
Si se especifica el parámetro opcional delimiter, éste también será escapado. Esto es útil para escapar el delimitador que es necesario para las funciones PCRE. El delimitador / es el que se usa comúnmente.
Valores devueltos
Devuelve la cadena escapada.
Historial de cambios
| Versión | Descripción |
|---|---|
| 5.3.0 | El carácter - ahora es escapado |
Ejemplos
Example #1 Ejemplo de preg_quote()
<?php
$claves = '$40 por un a g3/400';
$claves = preg_quote($claves, '/');
echo $claves; // devuelve \$40 por un g3\/400
?>
Example #2 Poner en cursiva una palabra dentro de un texto
<?php
// En este ejemplo, preg_quote($palabra) se usa para que los
// asteriscos sigan teniendo un significado especial en la
// expresión regular.
$texto = "Este libro es *muy* difícil de encontrar.";
$palabra = "*muy*";
$texto = preg_replace ("/" . preg_quote($palabra) . "/",
"<i>" . $palabra . "</i>",
$texto);
?>
Notas
Note: Esta función es segura binariamente.
To escape characters with special meaning, like: .-[]() and so on, use \Q and \E.
For example:
<?php echo ( preg_match('/^'.( $myvar = 'te.t' ).'$/i', 'test') ? 'match' : 'nomatch' ); ?>
Will result in: match
But:
<?php echo ( preg_match('/^\Q'.( $myvar = 'te.t' ).'\E$/i', 'test') ? 'match' : 'nomatch' ); ?>
Will result in: nomatch
Not sure why this note got deleted, but hey lets try again:
As of PHP 5.3, bug #47229 has been fixed and preg_quote *will* escape a hyphen (-). This may effect your code so ensure this is one thing you check when moving to 5.3.
I wanted to escape a string of characters so I could match them in [], i.e. [.,-!"§$%\\\[\]\^].
Unfortunately preg_quote does not escape the - character which has a special meaning in [], i.e. [a-z].
So I used this hack: make - the delimiter of the expression, i.e.
preg_quote(userinput, "-")
preg_replace("-[$userinput]-u", "", $str)
Apparently using a special char as a delimiter of a regular expression disables this character, i.e. even if it's escaped it's not understood as special character for the expression anymore.
so the pattern "-[a\\-z]-u" matches the characters a, - and z, and not abc...xyz.
It would be nice if preg_quote also escaped characters that have special meanings even if they have this meaning only under certain conditions, such as inside [].
To bizzigul at hotmail dot fr:
It's not a good practice to make somthing work *almost* all of the time. If the input contains a '`' you will still get an error. I recommend using the default delimiter ('/') and also feed this to preg_quote as second argument.
To prevent any problems, try to always use a delimiter that will *almost* not be used inside the regex, such as ` (back quote)
for example: instead of
<?php preg_match('/foo\/bar\//',$somevar); ?>
use
<?php preg_match('`foo/bar/`',$somevar); ?>
it's that simple! like this, you won't have to bother with delimiters anymore...
Wondering why your preg_replace fails, even if you have used preg_quote?
Try adding the delimiter / - preg_quote($string, '/');
