← Back to Chapters

PHP addslashes() & stripslashes()

? PHP addslashes() & stripslashes()

? Quick Overview

PHP provides addslashes() and stripslashes() to escape and unescape special characters in strings. They are commonly used when dealing with quotes, backslashes, or user input before storing or displaying data.

? Key Concepts

  • addslashes() adds escape characters to quotes, backslashes, and NULL.
  • stripslashes() removes escape characters added earlier.
  • Useful for basic string safety but not a replacement for prepared SQL statements.

? Syntax / Theory

  • addslashes(string) → returns escaped string
  • stripslashes(string) → returns original string

? Example 1: Using addslashes()

? View Code Example
// Escaping quotes and special characters
<?php
$string = "He said, \"Hello, World!\"";
$escaped = addslashes($string);
echo $escaped;
?>

? Explanation

The addslashes() function inserts backslashes before double quotes, making the string safer for storage or processing.

? Example 2: Using stripslashes()

? View Code Example
// Removing escape characters from a string
<?php
$escaped = "He said, \"Hello, World!\"";
$unescaped = stripslashes($escaped);
echo $unescaped;
?>

? Explanation

stripslashes() restores the original readable string by removing added backslashes.

✨ Example 3: Combined Usage

? View Code Example
// Safely storing and retrieving user input
<?php
$userInput = "O'Reilly";
$escaped = addslashes($userInput);
$retrieved = stripslashes($escaped);
echo $retrieved;
?>

? Live Output

The output correctly displays: O'Reilly

? Interactive Concept

Think of addslashes() as putting protective armor on quotes, and stripslashes() as removing that armor when it’s safe to display.

? Use Cases

  • Escaping strings before temporary storage
  • Handling quoted user input
  • Basic data cleaning during legacy PHP development

✅ Tips & Best Practices

  • Use prepared statements for database queries instead of manual escaping.
  • Apply stripslashes() only when needed to avoid data loss.
  • Always validate and sanitize user input.

? Try It Yourself

  • Escape a sentence containing both single and double quotes.
  • Store escaped text in a variable and restore it.
  • Test how backslashes affect output formatting.