PHP - Escape Characters

In PHP, escape characters are used to insert special characters into strings—especially within double-quoted (" ") or heredoc strings. They’re introduced with a backslash (\).

Common Escape Sequences in PHP

Escape Sequence Meaning
\n New line (line feed)
\r Carriage return
\t Horizontal tab
\\ Backslash
\" Double quote
\$ Dollar sign
\v Vertical tab (less common)
\f Form feed (less common)

Example

<?php echo "Line 1\nLine 2\n"; // Output on two lines echo "She said, \"Hello!\"\n"; // Escaped double quotes echo "This costs \$10"; // Escapes the dollar sign ?>

Important Notes

  • Single-quoted strings (' ') do not parse most escape sequences—only \\ and \' are recognized:

    echo 'It\'s PHP\\Code'; // Output: It's PHP\Code
  • Use heredoc (<<<) or nowdoc (<<<') for multi-line strings, with similar escape rules:

    • Heredoc behaves like double-quoted strings (parses escape characters).

    • Nowdoc behaves like single-quoted strings (no escape character parsing except \\ and \').