PHP 和控制台 Chrome 上 V8J 中 RegExp 的差异结果

Difference result for RegExp in the V8Js on PHP and Console Chrome

我有这个 JS 代码:

var str = "foo bar";
var res1 = str.replace(new RegExp('foo\b', 'g'), "BAZ");
var res2 = str.replace(new RegExp('foo', 'g'), "BAZ");
console.log("Result1: " + res1 + " Result2: " + res2);

Chrome Version 69.0.3497.81 (Official Build) (64-bit) 控制台的结果是:

Result1: BAZ bar Result2: BAZ bar

现在我在 PHP 上用 V8Js 扩展测试相同的代码:

PHP代码:

<?php
$v8 = new V8Js();
$JS = <<<EOT
var str = "foo bar";
var res1 = str.replace(new RegExp('foo\b', 'g'), "BAZ");
var res2 = str.replace(new RegExp('foo', 'g'), "BAZ");
print("Result1: " + res1 + " Result2: " + res2);
EOT;
echo $v8->executeString($JS);

PHP 7.2.9 (cli) (built: Aug 15 2018 05:57:41) ( NTS MSVC15 (Visual C++ 2017) x64 ) 扩展名 V8Js Version 2.1.0 的结果:

Result1: foo bar Result2: BAZ bar

为什么 result1 的结果不同?!!!

您正在使用 Heredoc,这等同于 "
这意味着它会将 \ 解释为转义。

如果您使用 Nowdoc 它将等同于 ' 因此不会转义反斜杠。

当你阅读手册时,这并不完全明显,但你需要阅读 Nowdoc 才能看到 Heredoc 是双引号。

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings.

这意味着将您的字符串声明更改为:

$JS = <<<'EOD'
var str = "foo bar";
var res1 = str.replace(new RegExp('foo\b', 'g'), "BAZ");
var res2 = str.replace(new RegExp('foo', 'g'), "BAZ");
print("Result1: " + res1 + " Result2: " + res2);
EOD;