PHP Escape Slash

← Back to Index


Example 1: WITH Escape Slash

$quote = "She said, \"PHP is awesome!\"";
echo $quote;
    

Output: She said, "PHP is awesome!"


Example 2: WITHOUT Escape Slash

// This would cause a PHP PARSE ERROR:
// $quote = "She said, "PHP is awesome!"";
//                      ^ PHP ends the string here!

// Safe demonstration using single quotes instead:
$quote = 'She said, "PHP is awesome!"';
echo $quote;
    

Output: She said, "PHP is awesome!"


Explanation

In PHP, the escape slash (backslash \) tells the interpreter that the character immediately following it should be treated as a literal character rather than having its special meaning. When you write \" inside a double-quoted string, the backslash escapes the double quote, preventing PHP from interpreting it as the end of the string. Without the escape slash, placing a double quote inside a double-quoted string causes a PHP parse error that breaks the entire script. The escape slash also works for other special characters such as \n (newline), \t (tab), and \\ (a literal backslash). Proper use of escape characters is essential for building strings that contain special characters safely in PHP.

INFOST 440 — Activity 3 — Nyla Broughton