Quoting PHP Strings
25 Aug 2005PHP developers generally understand the difference between using single quotes versus double quotes to enclose a string. If you need stuff to be interpreted, you use double quotes. If you need to indicate a literal string, you use single quotes:
$string = 'two';
echo '<p>one $string three</p>';
echo "<p>one $string three</p>";
Do you know what this will output? I think most of you do. You'll see the variable name on the first line and its value on the second:
Try this one:
$one = 'the\quick\brown\fox';
$two = 'the\\quick\\brown\\fox';
$three = 'the\\\quick\\\brown\\\fox';
$four = 'the\\\\quick\\\\brown\\\\fox';
echo "<p>$one</p><p>$two</p><p>$three</p><p>$four</p>";
It surprises many people to see that this code produces the following:
the\quick\brown\fox
the\\quick\\brown\\fox
Although it's not necessary to escape backslashes inside a string enclosed with single quotes, two consecutive backslashes are interpreted as one. Surprised?
If you want a string that contains single quotes, you need to escape them with a backslash (or enclose the string with double quotes:
$name = 'O\'Reilly';
$name = "O'Reilly";
What do you do if you need to have a backslash followed by a single quote in your string? You have to escape both:
echo 'Escape single quotes like this: \\\'';
This will output the proper instructions for escaping a single quote:
Therefore, within a string enclosed with single quotes, PHP needs to allow both single quotes and backslashes to be escaped. I'm not sure if this is explained very clearly in the manual:
To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to escape any other character, the backslash will also be printed!
Hopefully it all makes more sense now. :-)