PHP Escape Characters
Some characters can't be typed directly into a string because PHP would misread them. A common case is a double quote inside a string that is itself wrapped in double quotes: PHP takes it as the end of the string.
The solution is an escape character. Write a backslash \ and then the character you want, and PHP treats that character as ordinary text.
Example
The quotes around Vikings end the string too early, so PHP stops with a parse error:
Prompt
Write a PHP script that tries to use double quotes inside a double-quoted string without escaping, causing an error. Store "We are the so-called "Vikings" from the north." in a variable and echo it.
Output: PHP script
index.php
<?php
$x = "We are the so-called "Vikings" from the north.";
echo $x;
?>
Example
Putting a backslash in front of each inner quote, as \", solves the problem:
Prompt
Write a PHP script that uses the backslash escape character to include double quotes inside a double-quoted string. Store "We are the so-called "Vikings" from the north." in a variable and echo it.
Output: PHP script
index.php
<?php
$x = "We are the so-called \"Vikings\" from the north.";
echo $x;
?>
Escape Characters
The backslash works with more than quotes. PHP also understands these other sequences:
Escape Characters Table
Here is what each sequence stands for:
index.php
\' Single Quote
\" Double Quote
\$ PHP variables
\n New Line
\r Carriage Return
\t Tab
\f Form Feed
\ooo Octal value
\xhh Hex value