How to Escape a Runtime PHP String Containing Regular Expression Special Characters?

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'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.