Text to escape

PHP String Type:

Escaped text

Why escape text in PHP?

Escaping PHP strings is necessary when you want to include special characters in string literals. Proper escaping prevents syntax errors and ensures that your strings are interpreted correctly by the PHP interpreter.

Examples of PHP escaping

Original text

$name = "John O'Connor";
$message = "Hello, this is a "test" message with $variables";
$path = "C:\Program Files\PHP\php.exe";
$multiline = "This is a
multiline string
with special chars: ', ", \, $var";
$heredoc = <<<EOD
This is a heredoc string
with $variables and "quotes"
EOD;

Escaped text (single)

$name = "John O\'Connor";
$message = "Hello, this is a "test" message with $variables";
$path = "C:\\Program Files\\PHP\\php.exe";
$multiline = "This is a
multiline string
with special chars: \', ", \\, $var";
$heredoc = <<<EOD
This is a heredoc string
with $variables and "quotes"
EOD;

PHP String Types and Escaping

Single-quoted Strings

In single-quoted strings, only a few characters need to be escaped:

  • Single quote (') becomes \'
  • Backslash (\) becomes \\

Example: 'O\'Reilly'

Note: Variables are not interpolated in single-quoted strings, so $variable is treated as literal text.

Double-quoted Strings

Double-quoted strings support more escape sequences and variable interpolation:

  • Double quote (") becomes \"
  • Dollar sign ($) becomes \$ (to prevent variable interpolation)
  • Backslash (\) becomes \\
  • Newline (\n) becomes \\n
  • Carriage return (\r) becomes \\r
  • Tab (\t) becomes \\t
  • Form feed (\f) becomes \\f
  • Vertical tab (\v) becomes \\v
  • Null byte (\0) becomes \\0

Example: "Path: C:\\Program Files\\PHP"

Heredoc Syntax

Heredoc strings behave like double-quoted strings but have a different syntax:

$text = <<<EOD
This is a heredoc string with $variables
EOD;

The same escape sequences as double-quoted strings apply, but you don't need to escape the delimiter (EOD).

When to use PHP escaping

  • When including user input in PHP string literals
  • When working with strings that contain quotes, backslashes, or other special characters
  • When generating PHP code programmatically
  • When you need to prevent variable interpolation in double-quoted strings

Security Note:

While escaping is important for syntax correctness, it's not sufficient for security. When handling user input that will be used in a database query, use prepared statements. For output to HTML, use appropriate HTML escaping functions.

Related Tools

All Tools

See all available tools