user2839497 user2839497 - 23 days ago 9
Javascript Question

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

I've a following working JavaScript code which makes use of \ escape character

This backslash escape character turns special characters into string characters

<!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>


The output of above code in browser is as below :

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


My question is does the implementation of \ escape character work in similar manner in PHP as well or are there any differences in implementation in PHP?

Thank You.

Answer

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

Yes.

or are there any differences in implementation in PHP?

Yes. There are two significant differences with regard to the backslash as an escape:

  • In PHP, the use of the backslash as an escape is very different depending on whether you use a single-quoted string ('foo') or double-quoted string ("foo").

  • The escape sequences are different, although there is a lot of overlap.

Single-quoted vs. Double-quoted

In PHP there's a big difference between single-quoted and double-quoted strings in terms of escape sequences (and more, see ¹ below). Details in the documentation, but in single-quoted strings, the backslash is only an escape character if the next character is a ' or a backslash; in all other cases, it's a literal backslash. So

echo 'foo\nbar';

outputs

foo\nbar

whereas

echo "foo\nbar";

outputs

foo
bar

In JavaScript, the only difference between a single-quoted string and a double-quoted string is whether a ' or " can appear unescaped. The escape sequences that you can use in both are exactly the same.

Escape sequences

The PHP documentation linked above lists the PHP escape sequences. The JavaScript spec lists the JavaScript escape sequences, although MDN's list is easier to read. Again, there's a lot of overlap (both are inspired by C), but there are also differences.


¹ And as long as we're talking about PHP strings and JavaScript strings, note that in double-quoted PHP strings, variables are expanded; in single-quoted ones, they aren't. JavaScript doesn't have that, but it does have something similar (and even more powerful) with the new template literals in ES2015.