To match a literal backslash, many people and the PHP manual say: Always triple escape it, like this \\\\
Note:
Single and double quoted PHP strings have special meaning of backslash. Thus if \ has to be matched with a regular expression
\\
, then"\\\\"
or'\\\\'
must be used in PHP code.
Here is an example string: \test
$test = "\\test"; // outputs \test;
// WON'T WORK: pattern in double-quotes double-escaped backslash
#echo preg_replace("~\\\t~", '', $test); #output -> \test
// WORKS: pattern in double-quotes with triple-escaped backslash
#echo preg_replace("~\\\\t~", '', $test); #output -> est
// WORKS: pattern in single-quotes with double-escaped backslash
#echo preg_replace('~\\\t~', '', $test); #output -> est
// WORKS: pattern in double-quotes with double-escaped backslash inside a character class
#echo preg_replace("~[\\\]t~", '', $test); #output -> est
// WORKS: pattern in single-quotes with double-escaped backslash inside a character class
#echo preg_replace('~[\\\]t~', '', $test); #output -> est
Conclusion:
- If the pattern is single-quoted, a backslash has to be double-escaped
\\\
to match a literal \ - If the pattern is double-quoted, it depends whether
the backlash is inside a character-class where it must be at least double-escaped
\\\
outside a character-class it has to be triple-escaped\\\\
Who can show me a difference, where a double-escaped backslash in a single-quoted pattern e.g. '~\\\~'
would match anything different than a triple-escaped backslash in a double-quoted pattern e.g. "~\\\\~"
or fail.
When/why/in what scenario would it be wrong to use a double-escaped \
in a single-quoted pattern e.g. '~\\\~'
for matching a literal backslash?
If there's no answer to this question, I would continue to always use a double-escaped backslash \\\
in a single-quoted PHP regex pattern to match a literal \
because there's possibly nothing wrong with it.