// 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.

Answer from MikeM on Stack Overflow
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{0}</b>', __FILE__ );
🌐
PHP
php.net › manual › en › regexp.reference.escape.php
PHP: Escape sequences - Manual
If a pattern is compiled with the ... newline character are ignored. An escaping backslash can be used to include a whitespace or "#" character as part of the pattern....
🌐
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
Sometimes it might be better to use different delimiters. Especially when you have some forward slashes in your regex: // Backslash $regex = '/^\/user\/(\d+)\/?/i'; // Clean $regex = '~^/user/(\d+)/?~i';
Author: Hamz-a
🌐
Develop Websites
developwebsites.net › home › php › how to match a backslash with preg_match() in php
How to Match A Backslash with preg_match() in PHP
May 5, 2025 - I’d hazard a guess that the final backslash is escaping the forward slash that completes the regular expression. Actually you would only use three slashes to represent a literal slash: ‘/\\\/’ ... Although 3 slashes may appear to work (don’t ask me why!), the correct way in PHP is definitely to use 4 slashes: http://www.php.net/manual/en/regexp.reference.escape.php
🌐
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 ...
🌐
Namaste UI
namasteui.com › home › php › match a backslash with preg_match() in php
Match a backslash with preg_match() in PHP
May 20, 2021 - A backslash(“\”) is used to escape a special characters in regular expression so that they will be interpreted literally in the pattern itself.
🌐
BrainBell
brainbell.com › php › escaping-special-characters-in-regular-expressions.html
Escaping special characters in regular expressions in PHP – BrainBell
Escaping the special meaning of a character is done with the backslash character as with the expression "2\+3", which matches the string "2+3". If the + isn’t escaped, the pattern matches one or many occurrences of the character 2 followed by the character 3. ... <?php $string = 'Hi, 2+3 ...
🌐
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 ...
🌐
Beamtic
beamtic.com › excaping-backslash-php
Escaping Backslash in PHP | Beamtic
December 26, 2020 - For example, I created a regular expression to replace both forward slash and backslash from file paths, including duplicate slashes like "//", however, I kept getting errors because the backslash was not properly escaped. With preg_replace, backslash needs to be double escaped:
Find elsewhere
🌐
SSOJet
ssojet.com › escaping › regex-escaping-in-php
Regex Escaping in PHP | Escaping Techniques in Programming
Characters such as ., *, +, ?, ^, $, (, ), [, ], {, }, |, and \ all act as metacharacters. To match these characters literally within your PHP regex pattern, you must escape them by preceding them with a backslash (\).
Top answer
1 of 2
4

The backslash has a special meaning in both regexen and PHP. In both cases it is used as an escape character. For example, if you want to write a literal quote character inside a PHP string literal, this won't work:

$str = ''';

PHP would get "confused" which ' ends the string and which is part of the string. That's where \ comes in:

$str = '\'';

It escapes the special meaning of ', so instead of terminating the string literal, it is now just a normal character in the string. There are more escape sequences like \n as well.

This now means that \ is a special character with a special meaning. To escape this conundrum when you want to write a literal \, you'll have to escape literal backslashes as \\:

$str = '\\'; // string literal representing one backslash

This works the same in both PHP and regexen. If you want to write a literal backslash in a regex, you have to write /\\/. Now, since you're writing your regexen as PHP strings, you need to double escape them:

$regex = '/\\\\/';

One pair of \\ is first reduced to one \ by the PHP string escaping mechanism, so the actual regex is /\\/, which is a regex which means "one backslash".

2 of 2
0

I think you can use "preg_quote()":

http://php.net/preg_quote

This function escapes special chars, so you can give an input as it is, without escaping by yourself:

<?php
$string = "online 24/7. Only for \o/";
$escaped_string = preg_quote($string, "/"); // 2nd param is optional and used if you want to escape also the delimiter of your regex
echo $escaped_string; // $escaped_string: "online 24\/7.  Only for \\o\/"
?>
🌐
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?'
🌐
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 ...
🌐
PHP
durak.org › sean › pubs › software › php › regexp.reference.escape.html
Escape sequences - PHP 5.34 Documentation
This applies whether or not the following character would otherwise be interpreted as a meta-character, so it is always safe to precede a non-alphanumeric with "\" to specify that it stands for itself. In particular, if you want to match a backslash, you write "\\". ... Single and double quoted ...
🌐
YouTube
youtube.com › hey delphi
PHP : Right way to escape backslash [ \ ] in PHP regex? - YouTube
PHP : Right way to escape backslash [ \ ] in PHP regex?To Access My Live Chat Page, On Google, Search for "hows tech developer connect"I promised to share a ...
Published: May 17, 2023
Views: 13
Authors: David SklarAdam Trachtenberg
Published: 2002
Pages: 640
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);