Quoting PHP Strings

25 Aug 2005

PHP 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:

  1.  
  2. $string = 'two';
  3.  
  4. echo '<p>one $string three</p>';
  5. echo "<p>one $string three</p>";
  6.  

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:

  1.  
  2. $one   = 'the\quick\brown\fox';
  3. $two   = 'the\\quick\\brown\\fox';
  4. $three = 'the\\\quick\\\brown\\\fox';
  5. $four  = 'the\\\\quick\\\\brown\\\\fox';
  6.  
  7. echo "<p>$one</p><p>$two</p><p>$three</p><p>$four</p>";
  8.  

It surprises many people to see that this code produces the following:

  1. the\quick\brown\fox
  2. 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:

  1.  
  2. $name = 'O\'Reilly';
  3. $name = "O'Reilly";
  4.  

What do you do if you need to have a backslash followed by a single quote in your string? You have to escape both:

  1.  
  2. echo 'Escape single quotes like this: \\\'';
  3.  

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. :-)