Escaping characters is basic, but essential to an error-free PHP script. Consider the following sentence for example:
Mike’s uncle said, “Isn’t that cool?”
Now if we attempt to use PHP to echo this sentence to the browser, those quotes and apostrophes will cause some problems. The quotes and apostrophes inside the string are confused for the symbols used to signify the end of a string. The backslash (\) is used to “escape” characters that might have a special meaning to PHP if interpreted by the web server. A backslash before a character causes it to be treated just as a literal character, not as any special symbol. So, let’s go back and see how we could echo out that previous sentence.
Now only the first and last quotation marks will be interpreted as meaningful to PHP; the others are just characters as far as it is concerned. Below is a list of special characters that can be denoted with the backslash escape character.
Escape Sequence | Meaning | |
\\’ | Apostrophe | |
\\” | Quotation Mark | |
\\ | Backslash | |
\\$ | Dollar Sign | |
\\n | Newline | |
\\r | Carriage Return | |
\\t | Tab |
Now there are a few things to take note of here. For starters, let’s take the following bit of code:
PHP will replace $applicant with the variables value (“Mike”) – so instead of printing out Hello $applicant, it will print Hello Mike. This rather convenient replacement is variable expansion. However there may be times when you don’t want to do this. Maybe you want to actually use the name of a variable and echo that, rather than it’s value. We can accomplish that by simply escaping the $ before the variable name:
The first occurrence of $applicant is escaped, so PHP literally prints out $applicant. The second occurrence is not escaped, so PHP replaces it with the variables value of Mike. You can also suppress variable expansion by using single quotes instead of double quotes around a string. For example:
Leave a comment