The preg_quote Function
The preg_quote function adds backslashes before special regular expression characters. The first parameter is the string to be escaped, the second (optional) is the character that also needs to be escaped.
Syntax
preg_quote(string, [delimiter]);
Example
Escaping a string with special characters:
<?php
$str = 'price is .99 (50% off)';
echo preg_quote($str);
?>
Code execution result:
'price is $10\.99 \(50\% off\)'
Example
Escaping with an additional delimiter character:
<?php
$str = 'user/data/file.txt';
echo preg_quote($str, '/');
?>
Code execution result:
'user\/data\/file\.txt'
Example
Usage in a regular expression:
<?php
$search = 'file*.txt';
$pattern = '/^' . preg_quote($search, '/') . '$/';
echo $pattern;
?>
Code execution result:
'/^file\*\.txt$/'
See Also
-
the
preg_matchfunction,
which performs a match against a regular expression -
the
preg_replacefunction,
which performs a search and replace using a regular expression