Escaping A Regex¶
<?php
$regex = 'test.';
// match
print preg_match('/^'.$regex.'$/i', 'tests') ? 'match' : 'nomatch';
print PHP_EOL;
// nomatch
print preg_match('/^'.preg_quote($regex).'$/i', 'tests') ? 'match' : 'nomatch';
print PHP_EOL;
// nomatch
print preg_match('/^\Q'.$regex.'\E$/i', 'tests') ? 'match' : 'nomatch';
print PHP_EOL;
?>
To use literal characters inside a regex, it is possible to use preg_quote(): it adds a backslash before every special character in the string. Don’t forget to use the second argument, which can hold any arbitrary delimiter.
Another option is to use the \Q and \E characters inside the regex: it turns all the special characters into a literal value.
See Also¶
PHP Features¶
Last updated: 14 July 2026