How to Escape a Run-Time PHP String Containing Regular Expression Special Characters?

Learn how to escape a run-time string containing regex meta-characters in PHP

If you have a run-time string that may contain any of the regular expression special characters, then you can use the preg_quote() function to escape them. It will escape the following characters:

\ ^ $ . [ ] | ( ) ? * + { } = ! < > : - #

For example:

$str = 'hello world! how are you?';
$var = 'hello world!';

$replaceWith = 'foo,';
$pattern = '/' . preg_quote($var) . '/'; // '/hello world\!/'

echo preg_replace($pattern, $replaceWith, $str); // 'foo, how are you?'

If the delimiter character (i.e. the character that's used to enclose the regular expression pattern) is being used in the pattern itself, then you should specify the delimiter character as the second argument to the preg_quote() function to escape that character in the pattern. For example:

$str = 'hello/world';
$pattern = '/' . preg_quote($str, '/') . '/'; // '/hello\/world/'
$replaceWith = 'foo bar';

echo preg_replace($pattern, $replaceWith, $str); // 'foo bar'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.