\ 转义字符的实现在 JavaScript 和 PHP 中是否类似,或者这两种实现有什么不同?

Does the implementation of \ escape character work similarly in JavaScript and PHP or is there any difference in both the implementations?

我有以下工作 JavaScript 代码,它使用 \ 转义字符

这个反斜杠转义字符将特殊字符转换为字符串字符

<!DOCTYPE html>
<html>
  <body>

    <p id="demo"></p>

    <script>

      var x = 'It\'s alright';
      var y = "We are the so-called \"Vikings\" from the north.";

      document.getElementById("demo").innerHTML = x + "<br>" + y; 

    </script>

  </body>
</html>

以上代码在浏览器中的输出如下:

It's alright
We are the so-called "Vikings" from the north.

我的问题是 \ 转义字符的实现在 PHP 中是否也以类似的方式工作,或者在 PHP 中的实现是否有任何差异?

谢谢。

My question is does the implementation of \ escape character work in similar manner in PHP as well [as JavaScript]

是的。

or are there any differences in implementation in PHP?

是的。将反斜杠作为转义符有两个显着差异:

  • 在PHP中,反斜杠作为转义符的使用非常不同,具体取决于您使用的是单引号字符串 ('foo') 还是双引号字符串("foo").

  • 转义序列不同,虽然有很多重叠。

单引号与双引号

在 PHP 中,单引号和双引号字符串在转义序列方面存在很大差异(以及更多信息,请参见下面的 ¹)。 Details in the documentation,但在单引号字符串中,如果下一个字符是 ' 或反斜杠,反斜杠只是转义字符;在所有其他情况下,它是一个字面上的反斜杠。所以

echo 'foo\nbar';

产出

foo\nbar

echo "foo\nbar";

产出

foo
bar

在 JavaScript 中,单引号字符串和双引号字符串之间的唯一区别是 '" 是否可以显示为未转义。您可以在两者中使用的转义序列完全相同。

转义序列

PHP documentation linked above lists the PHP escape sequences. The JavaScript spec lists the JavaScript escape sequences, although MDN's list 更易读。同样,有很多重叠(均受 C 启发),但也有差异。


¹ 只要我们谈论 PHP 字符串和 JavaScript 字符串,请注意在双引号 PHP 字符串中,变量被扩展;在单引号中,它们不是。 JavaScript 没有那个,但它确实与 ES2015 中的新 template literals 有类似(甚至更强大)的东西。