Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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: 10 September 2026