要匹配字面反斜杠,很多人和the PHP manual说:总是三重逃避它,像这样 \\\\
注意:单引号和双引号PHP字符串具有反斜杠的特殊含义 . 因此,如果\必须与正则表达式\匹配,则必须在PHP代码中使用“\\”或“\\” .
这是一个示例字符串: \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 :
如果模式是单引号,则反斜杠必须双重转义 \\\ 以匹配文字\
如果模式是双引号,则取决于反向是否在字符类中,它必须至少双重转义 \\\ 在字符类之外它必须进行三重转义 \\\\
谁可以向我展示一个区别,例如单引号模式中的双重反斜杠,例如: '~\\\~' 将匹配任何不同于双引号模式中的三重转义反斜杠,例如 "~\\\\~" 或失败 .
何时/为什么/在什么情况下使用单引号模式中的双重转义 \ 是错误的,例如 '~\\\~' 用于匹配文字反斜杠?
如果对这个问题没有答案,我会继续在单引号的PHP正则表达式模式中使用双重转义反斜杠 \\\ 来匹配文字 \ ,因为它可能没有任何问题 .