ADVERTISEMENT
ADVERTISEMENT

Escape Special Characters in PHP with Examples

When working with strings in PHP, you often need to include characters that have special meanings (like quotes, backslashes, or newlines). To use these characters as normal text, you need to escape them using a backslash (). This tutorial explains how to handle special characters with examples.

What Are Special Characters?

Special characters are symbols that PHP treats differently. For example:

  • Quotes (' ")

  • Backslash (\)

  • Newline (\n), Tab (\t), and more

To include them in a string, escape them with a backslash ().

Commonly Escaped Characters in PHP

Here are the most used escape sequences:

Escape Sequence Character Description
\" Double Quote Escapes double quotes in strings
\' Single Quote Escapes single quotes in strings
\\ Backslash Escapes a backslash
\n Newline Inserts a new line
\r Carriage Return Returns to the beginning of the line
\t Tab Inserts a horizontal tab
\$ Dollar Sign Escapes a dollar sign
\v Vertical Tab Inserts a vertical tab
\f Form Feed Advances to the next page in print
\0 Null Character Inserts a null character

 

Examples of Escaping Special Characters

<?php
echo "1. Double Quote: He said, \"Hello!\"\n";
echo '2. Single Quote: It\'s a great day!' . "\n";
echo "3. Backslash: This is a backslash: \\\n";
echo "4. Newline: First Line\nSecond Line\n";
echo "5. Carriage Return: Hello\rWorld\n";
echo "6. Tab: Column1\tColumn2\n";
echo "7. Dollar Sign: The price is \$100\n";
echo "8. Vertical Tab: Text1\vText2\n";
echo "9. Form Feed: Page1\fPage2\n";
echo "10. Null Character: Hello\0World\n";
?>

Output :

  1. Double Quote: Prints "Hello!" with escaped quotes.
  2. Single Quote: Prints 'It's a great day!' without syntax errors.
  3. Backslash: Displays a literal \.
  4. Newline (\n): Splits text into two lines.
  5. Carriage Return (\r): Overwrites “Hello” with “World” (visible in some terminals).
  6. Tab (\t): Adds horizontal space between words.
  7. Dollar Sign (\$): Prevents variable interpretation.
  8. Vertical Tab (\v): Adds vertical space (limited terminal support).
  9. Form Feed (\f): Advances to a new page in printers (rarely used in terminals).
  10. Null Character (\0): Ends strings in certain contexts (visible effect varies).

ADVERTISEMENT

ADVERTISEMENT