Share via:

Escaping Backslash in PHP

Backslash needs to be tediously excaped in PHP.


Edited: 2019-08-11 17:41

I recently had a very strange problem where a literal backslash would not work within PHP strings under some circumstances, even when using single quotes.

If a Backslash is located at the end of a single quoted string, the Backslash needs to be escaped. For this reason, it is probably best to always escape your Backslashes, since it will avoid confusion in the code.

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:

$str = 'c:\this/test//\\'; // Note. Escaping the backslash at the end to make it literal

echo preg_replace('#[/\\\\]+#', '/', $str);

Apparently you need to escape the backslash twice within a regular expression, hence the double escape "\\\\".

The output is:


Not escaping a backslash can result in an error like:

PHP Parse error: syntax error, unexpected end of file in backslash.php on line 5