How to Escape Regular Expression Special Characters in PHP?

Find out how to escape regex meta-characters in PHP

You can use the backslash character (i.e. \) to escape the regular expression special characters. For example:

$str = 'hello?';
$replaceWith = 'hey?';
$pattern = '/hello\?/';

echo preg_replace($pattern, $replaceWith, $str); // 'hey?'

Typically, you would surround your regular expression pattern within two forward slashes (e.g. /pattern/). However, you may use any non-alphanumeric, non-backslash, non-whitespace character as a delimiter. In any case, the character you use for the delimiter (to enclose the pattern within), if that character exists in the pattern, you must escape it too. For example:

$str = 'hello/world';
$replaceWith = 'foo bar';
$pattern = '/hello\/world/';

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

As you can see in the example / (forward slash) is used as a delimiter for the regular expression. This means that the / used in the $pattern must be escaped, otherwise it will result in an error.

To escape a run-time string that may contain regular expression special characters, you can use the preg_quote() function.

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