When you need to include characters in a string that are otherwise illegal, you can use an escape character.
An escape character is a backslash \
followed by the character you wish to include.
Example: Including Double Quotes in a String
Consider a situation where you want to include double quotes inside a string that is itself surrounded by double quotes:
PHP
x
$sentence = "This is a famous line from the '80s movie, \"Back to the Future.\"";
Common Escape Characters
Here are some common escape characters used in PHP:
Code | Result |
---|---|
\' | Single Quote |
\" | Double Quote |
\$ | PHP variables |
\n | New Line |
\r | Carriage Return |
\t | Tab |
\f | Form Feed |
\ooo | Octal value |
\xhh | Hex value |
Basic Example
To include a double quote in a string:
PHP
$quote = "The mechanic said, \"Your Harley is ready.\"";
echo $quote;
Single Quotes
To include a single quote in a string:
PHP
$announcement = 'We\'ll meet at the cafe at 5 o\'clock.';
echo $announcement;