为什么单个反斜杠和双反斜杠在正则表达式中执行相同的转义?

Why does a single backslash and a double backslash perform the same escaping in regex?

我正在尝试匹配 008/

preg_match('/008\//i', '008/', $matches);
preg_match('/008\//i', '008/', $matches);

我的问题是为什么这两个正则表达式都有效。我希望第二个有效,但为什么双反斜杠第一个有效?

因为 PHP 字符串中的 \ 表示 "escape the backslash"。由于 \/ 没有任何意义,因此不需要转义(即使有可能),因此它们的计算结果相同。

换句话说,这两个将打印相同的内容:

echo '/008\//i'; // prints /008\//i
echo '/008\//i';  // prints /008\//i

反斜杠是 one of the few characters that can get escaped in a single quoted string(明显的 \' 除外),这确保您可以创建诸如 'test\' 的字符串而无需转义最后一个引号。