Escaping characters

Sometimes a string needs to contain characters with special meanings that might be interpreted incorrectly. For example, the following line of code will not work, because the second quotation mark encountered in the word sister’s will tell the PHP parser that the string end has been reached. Consequently, the rest of the line will be rejected as
an error:

$text = 'My sister's car is a Ford'; // Erroneous syntax

To correct this, you can add a backslash directly before the offending quotation mark to tell PHP to treat the character literally and not to interpret it

$text = 'My sister\'s car is a Ford';

And you can perform this trick in almost all situations in which PHP would otherwise return an error by trying to interpret a character. For example, the following doublequoted string will be correctly assigned:

$text = "My Mother always said \"Eat your greens\".";

Additionally you can use escape characters to insert various special characters into strings such as tabs, new lines, and carriage returns. These are represented, as you might guess, by \t, \n, and \r. Here is an example using tabs to lay out a heading; it is included here merely to illustrate escapes, because in web pages there are always better ways to do layout:

$heading = "Date\tName\tPayment";

These special backslash-preceded characters work only in double-quoted strings. In single-quoted strings, the preceding string would be displayed with the ugly \t sequences instead of tabs. Within single-quoted strings, only the escaped apostrophe (\’) and escaped backslash itself (\\) are recognized as escaped characters.


You may also like...