Escape sequences

You can achieve the same effect in double-quoted strings by using the escape character, which, in PHP, is a backslash \.

Escape sequences, the combination of the escape character \ and a letter, are used to signify that the character after the escape character should be treated specially. For example, if you wanted to have the string "And then he said, "That is amazing!", which was true", you would need escape characters because you have double quotes inside double quotes. Here is a list of the escape sequences in PHP:


Print the next character as a double quote, not a string closer


Print the next character as a single quote, not a string closer


Print a new line character (remember our print statements?)


Print a tab character


Print a carriage return (not used very often)


Print the next character as a dollar, not as part of a variable


Print the next character as a backslash, not an escape character

Here is a code example of these escape sequences in action:

    $MyString = "This is an \"escaped\" string";
    $MySingleString = 'This \'will\' work';
    $MyNonVariable = "I have \$zilch in my pocket";
    $MyNewline = "This ends with a line return\n";
    $MyFile = "c:\\windows\\system32\\myfile.txt";

It is particularly common to forget to escape Windows-style file system paths properly, but as you can see, it is simply a matter of adding more backslashes in there. If you were to print $MyFile, you would get this:


This is because the escape characters are just to make sure PHP can read the string correctly - once the data has been read, it is converted into the original format.

Along the same lines, escape sequences only work in double-quoted strings - if you type 'Hello!\n\n\n', PHP will actually print out the characters \n\n\n rather than converting them to new lines. It is important to note that escape characters are just one character in files themselves, however they are represented as two in PHP because they cannot physically be typed using your keyboard.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Heredoc >>

Previous chapter: Whitespace

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.