PHP String Escape Sequences

Description

Escape sequences, the combination of the escape character \ and a letter, are used to signify the escape character.

Escape sequence

The valid escape sequences in PHP are shown in the following table.

Escape Meaning
\" Print the next character as a double quote rather than treating it as a string terminator
\' Print the next character as a single quote rather than treating it as a string terminator
\n Print a new line character
\t Print a tab character
\r Print a carriage return (used primarily on Windows)
\$ Print the next character as a dollar rather than treating it as part of a variable name
\\ Print the next character as a backslash rather than treating it as an escape character

Example

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


<?PHP/*from  ww  w .  j  a  v  a2s  .c om*/
$MyString = "This is an \"escaped\" string"; 
print $MyString;
$MySingleString = 'This \'will\' work'; 
print $MySingleString;
$MyNonVariable = "I have \$abc"; 
print $MyNonVariable;
$MyNewline = "This ends with a line return\n"; 
print $MyNewline;
$MyFile = "c:\\windows\\system32\\myfile.txt"; 
print $MyFile;
?>

The code above generates the following result.

Since the only escape sequence that works in single quotes is \', it is safe to use non-escaped Windows-style filenames in your single-quoted strings, like this:


<?PHP
$filename = 'c:\windows\me.txt'; 
print $filename; 
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone