PHP String Escape Sequences
In this chapter you will learn:
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 j a va 2 s . c o m
$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.
Next chapter...
What you will learn in the next chapter:
- What is PHP Variable substitution in String
- Example - PHP Variable substitution in String
- Example - Including More Complex Expressions within Strings
Home » PHP Tutorial » PHP String