PHP: Quote marks
'Hello' 'Goodbye' 'G' ' ' ''
Which ones of the five above are strings?
We have alread dealt with the first two and we know for sure they are
strings, as we've learnt that a string is a set of characters.
Any single symbol wrapped in quotation marks is a string. An empty string
'' is a string too. We consider a string anything enclosed in quotes, even a space or no symbols at all.
In the earlier lessons we used single quotes, but it's not the only way to specify strings. You can also use double quotes.
Imagine you want to print the phrase dragon's mother. The apostrophe before the letter s is a symbol identical to the single quotation mark. Let's try:
<?php print_r('Dragon's mother');
Such code is not going to work. According to PHP, the string started with a single quote and ended after the letter n. It was followed by
s mother without quotation marks, which means it wasn't a string. And then there was an opening quote that wasn't closed:
');. Such code is syntaсtically incorrect (you can even see it from the way the code is highlighted).
In such case we should use double quotes. The following code will work correctly:
<?php print_r("Dragon's mother");
Now the interpreter knows that the string started with a double quote, that means it must end with a matching double quote. And the single quote inside (apostrophe) becomes part of the string.
It works the other way round too. If we want to use double quotes inside the string, we must enclose the string in single quotes. This way it doesn't matter how many quotation marks of the other type we insert inside the string.
Now, what about a string like this:
Dragon's mother said "No"
It has both single and double quotes. How do we enclose it? We must somehow tell the interpreter that those quotation marks belong to the string rather than open or close strings.
In this case the escape character '\' is used. If a quotation mark (single or double) is preceeded by '\', it will tell the interpreter that it belongs to the string, rather then specifies the start or end of the string.
<?php print_r("Dragon's mother said \"No\"");
Note that we had to escape the double quote rather than single quote with '\', because the string itself is enclosed in double quotes. If it was wrapped in single quotes, then we would have to escape the apostrophe instead of double quotes.
Write a program that will print the following phrase to the screen:
"Khal Drogo's favorite word is "athjahakar""
The program must print this exact symbols. Pay attention to the type of quotes in the beginning and end of the string.