Escaping Characters
A string starts at the opening quotation mark (single or double) and ends at the next matching quotation mark. The presence of the other quotation mark type within a string has no meaning (the other quotation mark is just another character). These are both fine:
echo "It's my birthday.";
echo 'I said, "Hello".';
However, if you need to include the same type of quotation mark inside of a string, special steps need to be taken. The following will cause parse errors.
echo 'It's my birthday.'; // Error!
echo "I said, "Hello"."; // Error!
To correct this error, either switch the outside quotation marks or escape the problematic character by preceding it with a backslash:
echo 'It's my birthday.';
echo "I said, \"Hello\".";
This issue often arises when printing large amounts of HTML, with its many quoted attributes.
PHP has several special escape sequences. Unlike \', which has meaning within single quotation marks, these other escape sequences are only meaningful within double quotation marks (within single quotation marks each will be treated literally). There are a couple of other escape sequences, but these are the most useful.
Sequence |
Meaning |
\0 |
NULL |
\n |
newline |
\r |
carriage return |
\t |
tab |
\$ |
dollar sign |
\\ |
backslash |
\" |
double quotation mark |
heredoc Syntax
PHP supports an alternative string delimiter: the heredoc syntax. Instead of using quotation marks, a special character sequence is used to identify the beginning and ending of the string. The character sequence can be any alphanumeric plus the underscore combination but it cannot start with a number and it cannot be found within the string itself. Common choices are EOT and EOD:
$address = <<<EOT
1600 Pennsylvania Avenue
Washington DC
EOT;
echo <<<EOT
Hello, $name
EOT;
Any variables within the string will be parsed (their names will be replaced with their values) exactly as PHP handles double quotation marks. Note that the closing identifier (EOT in the code above) must appear in the first column of the file (no spaces or other characters can precede the identifier on the line). (The image at right shows how NuSphere's PhpED understands the heredoc syntax as well.)
Extra Notes
Although not often necessary, you can refer to an individual character within a string by using the array notation. As with any array, the first letter is at 0:
$name = 'Jon';
echo $name[0]; // Prints "J".
See also:
- Typecasting
- String Functions
|