Nabi K.A.Z.
Nabi K.A.Z.

Reputation: 10714

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

I have this JS code:

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);

The result on Console of Chrome Version 69.0.3497.81 (Official Build) (64-bit) is:

Result1: BAZ bar Result2: BAZ bar

Now I test same code on PHP with V8Js extension:

PHP code:

<?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);

Result on the PHP 7.2.9 (cli) (built: Aug 15 2018 05:57:41) ( NTS MSVC15 (Visual C++ 2017) x64 ) With V8Js Version 2.1.0 extension:

Result1: foo bar Result2: BAZ bar

Why difference result for result1?!!!

Upvotes: -1

Views: 71

Answers (1)

Andreas
Andreas

Reputation: 23958

You are using Heredoc which is equivalent with ".
That means it will interpret the \ as escaping.

If you use Nowdoc it will be equivalent with ' thus not escape the backslash.

It's not completley obvious when you read the manual but you need to read about Nowdoc to see that Heredoc is double quote.

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

That means change your string declaration to:

$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;

Upvotes: 2

Related Questions