Skip to content

PHP String Escaping

Syntax

In PHP, special characters can be escaped using the backslash (\) inside strings, especially in double-quoted strings.

// Escaping special characters
$quote = "She said, \"Hello!\""; // Escaping double quotes
$path = "C:\\xampp\\htdocs"; // Escaping backslashes
$singleQuote = 'It\'s PHP!'; // Escaping single quotes in single-quoted strings
// Escaping variables to prevent interpolation
$message = "This is a \$variable.";

Example

<?php
// Using escape sequences in strings
$greeting = "He said, \"Welcome to PHP programming!\"";
echo $greeting . "\n"; // Outputs: He said, "Welcome to PHP programming!"
// Escaping backslashes
$directory = "C:\\Users\\Admin\\Documents";
echo "Directory path: " . $directory . "\n"; // Outputs: Directory path: C:\Users\Admin\Documents
// Preventing variable interpolation
$literal = "This is a \$literal variable.";
echo $literal; // Outputs: This is a $literal variable.
?>