preg_quote() is what you are looking for:

Description

string preg_quote ( string $str [, string $delimiter = NULL ] )

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Parameters

str

The input string.

delimiter

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.

Example - using preg_match to find occurrences of a given URL surrounded by whitespace:

$url = 'http://stackoverflow.com/questions?sort=newest';

// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');

// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now:  /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);

var_dump($matches);
// array(1) {
//   [0]=>
//   string(48) " http://stackoverflow.com/questions?sort=newest "
// }
Answer from Tom Haigh on Stack Overflow
Top answer
1 of 2
280

preg_quote() is what you are looking for:

Description

string preg_quote ( string $str [, string $delimiter = NULL ] )

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax. This is useful if you have a run-time string that you need to match in some text and the string may contain special regex characters.

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

Parameters

str

The input string.

delimiter

If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

Importantly, note that if the $delimiter argument is not specified, the delimiter - the character used to enclose your regex, commonly a forward slash (/) - will not be escaped. You will usually want to pass whatever delimiter you are using with your regex as the $delimiter argument.

Example - using preg_match to find occurrences of a given URL surrounded by whitespace:

$url = 'http://stackoverflow.com/questions?sort=newest';

// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');

// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now:  /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);

var_dump($matches);
// array(1) {
//   [0]=>
//   string(48) " http://stackoverflow.com/questions?sort=newest "
// }
2 of 2
2

It would be much safer to use Prepared Patterns from T-Regx (i'm the author of the library):

$url = 'http://stackoverflow.com/questions?sort=newest';

$pattern = Pattern::inject('\s@\s', [$url]);
                                    // ↑ $url is quoted

then perform normal match:

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";

$matcher = pattern->match($haystack);
foreach ($matcher as $match) {
}

you can even use it with preg_match():

preg_match($pattern, 'foo', $matches);
🌐
PHP
php.net › manual › en › function.preg-quote.php
PHP: preg_quote - Manual
To escape characters with special meaning, like: .-[]() and so on, use \Q and \E. For example: <?php echo ( preg_match('/^'.( $myvar = 'te.t' ).'$/i', 'test') ? 'match' : 'nomatch' ); ?> Will result in: match But: <?php echo ( preg_match('/^\Q'.( ...
🌐
SSOJet
ssojet.com › escaping › regex-escaping-in-php
Regex Escaping in PHP | Escaping Techniques in Programming
PHP's preg_quote() function is designed for this exact purpose. It automatically escapes any characters within a string that have special meaning in regular expressions, ensuring they're treated as literal characters.
🌐
Regular-Expressions.info
regular-expressions.info › php.html
Using Regular Expressions with PHP
In PHP, this becomes preg_match('/regex/', $subject). When forward slashes are used as the regex delimiter, any forward slashes in the regular expression have to be escaped with a backslash. So https://www\.regexp\.info/ becomes '/https:\/\/www\.regexp\.info\//'. Just like Perl, the preg functions ...
🌐
MojoAuth
mojoauth.com › escaping › regex-escaping-in-php
Regex Escaping in PHP | Escaping Methods in Programming Languages
Regular expressions (regex) are powerful tools used for pattern matching and manipulation of strings in programming. However, regex syntax includes special characters that can alter the intended meaning of your patterns. This is where regex escaping comes into play. In PHP, escaping special characters ensures that they are treated as literal values rather than operators.
🌐
GitHub
github.com › Hamz-a › php-regex-best-practices › blob › master › 06 Escaping a backslash hell.md
php-regex-best-practices/06 Escaping a backslash hell.md at master · Hamz-a/php-regex-best-practices
$regex = <<<'regex' ~ fancy # fancy's explanation regex # note ^ no escape needed ~x regex; preg_match_all($regex, $input,$m); We used the nowdoc string syntax but we could also have used a heredoc. Read the difference from the manual. Don't forget that double quoted strings have a special power in php which means it might interfer with the regex.
Author: Hamz-a
🌐
Designcise
designcise.com › web › tutorial › how-to-escape-regular-expression-special-characters-in-php
How to Escape Regex Special Chars in PHP? - Designcise
June 4, 2021 - 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?'
🌐
GeeksforGeeks
geeksforgeeks.org › php › function-to-escape-regex-patterns-before-applied-in-php
Function to escape regex patterns before applied in PHP - GeeksforGeeks
July 12, 2025 - Use preg_quote() function in PHP to escape regex patterns before it is applied in run time. The preg_quote() function puts a backslash in front of every character within the specified string that would be a part of the regex syntax in PHP, thereby ...
Find elsewhere
🌐
DocStore
docstore.mik.ua › orelly › webprog › pcook › ch13_09.htm
Escaping Special Characters in a Regular Expression (PHP Cookbook)
You want to have characters such as * or + treated as literals, not as metacharacters, inside a regular expression. This is useful when allowing users to type in search strings you want to use inside a regular expression · Use preg_quote( ) to escape Perl-compatible regular-expression ...
🌐
Compile7
compile7.org › escaping › how-to-use-regex-escaping-in-php
How to use Regex Escaping in PHP | Escaping Methods in Programming Languages
Since PHP itself uses the backslash for its own string escapes (like \n for newline), you often need to double the backslash (\\) to escape the backslash itself. This ensures that \\. in your PHP string correctly becomes \. for the regex engine.
Authors: David SklarAdam Trachtenberg
Published: 2002
Pages: 640
Top answer
1 of 6
63
// PHP 5.4.1

// Either three or four \ can be used to match a '\'.
echo preg_match( '/\\\/', '\\' );        // 1
echo preg_match( '/\\\\/', '\\' );       // 1

// Match two backslashes `\\`.
echo preg_match( '/\\\\\\/', '\\\\' );   // Warning: No ending delimiter '/' found
echo preg_match( '/\\\\\\\/', '\\\\' );  // 1
echo preg_match( '/\\\\\\\\/', '\\\\' ); // 1

// Match one backslash using a character class.
echo preg_match( '/[\\]/', '\\' );       // 0
echo preg_match( '/[\\\]/', '\\' );      // 1  
echo preg_match( '/[\\\\]/', '\\' );     // 1

When using three backslashes to match a '\' the pattern below is interpreted as match a '\' followed by an 's'.

echo preg_match( '/\\\\s/', '\\ ' );    // 0  
echo preg_match( '/\\\\s/', '\\s' );    // 1  

When using four backslashes to match a '\' the pattern below is interpreted as match a '\' followed by a space character.

echo preg_match( '/\\\\\s/', '\\ ' );   // 1
echo preg_match( '/\\\\\s/', '\\s' );   // 0

The same applies if inside a character class.

echo preg_match( '/[\\\\s]/', ' ' );   // 0 
echo preg_match( '/[\\\\\s]/', ' ' );  // 1 

None of the above results are affected by enclosing the strings in double instead of single quotes.

Conclusions:
Whether inside or outside a bracketed character class, a literal backslash can be matched using just three backslashes '\\\' unless the next character in the pattern is also backslashed, in which case the literal backslash must be matched using four backslashes.

Recommendation:
Always use four backslashes '\\\\' in a regex pattern when seeking to match a backslash.

Escape sequences.

2 of 6
19

To avoid this kind of unclear code you can use \x5c Like this :)

echo preg_replace( '/\x5c\w+\.php$/i', '<b>${0}</b>', __FILE__ );
🌐
Exakat
php-tips.readthedocs.io › en › latest › tips › escaped_regex.html
Escaping A Regex
June 17, 2025 - Escaping A Regex: 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.
🌐
PHP.Watch
php.watch › articles › php-regex-readability
Writing better Regular Expressions in PHP • PHP.Watch
May 26, 2021 - Not choosing meta characters (such as ``, $, braces, and other characters that carry special meaning in regular expressions) can reduce the number of characters escaped.