PHP preg_quote() Function
The PHP preg_quote() function puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.
The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #
Please note that / is not a special regular expression character.
Syntax
preg_quote(str, delimiter)
Parameters
str |
Required. Specify the input string. |
delimiter |
Optional. When specified (a single character), it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter. Default is null. |
Return Value
Returns the quoted (escaped) string.
Example: preg_quote() example
The example below shows the usage of preg_quote() function.
<?php //a string which need to be escaped $str = 'send $100 to D/303'; //using preg_quote function $str = preg_quote($str, '/'); //displaying the result echo $str; ?>
The output of the above code will be:
send \$100 to D\/303
Example: italicizing a word within given text
In the example below a word containing asterisks is italicized. As asterisk has special meaning in the regular expression. Therefore it is first escaped using preg_quote() function.
<?php //asterisk has special meaning in the regular //expression, therefore it should be escaped first $str = "This book is *very* difficult to find."; $word = "*very*"; //italicizing the $word $str = preg_replace ("/".preg_quote($word, '/')."/", "<i>".$word."</i>", $str); //displaying the result echo $str; ?>
The output of the above code will be:
This book is <i>*very*</i> difficult to find.
❮ PHP RegEx Reference