Content · Programming · PHP

PHP addslashes() Function: Usage and Examples

Learn how PHP addslashes works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

Prefixes certain characters such as quotes and backslashes with a backslash.

What Is addslashes() in PHP?

Prefixes certain characters such as quotes and backslashes with a backslash.

Its syntax is:

addslashes(string $string): string

Parameters:

  • $string — Accepted as string; required argument.

Return type: string. Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.

Availability: Available in standard PHP.

Example 1: Basic Usage

<?php

echo addslashes("Don't");

Output:

Don\'t

Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.

Example 2: A Different Input

<?php

echo addslashes('He said "Hello"');

Output:

He said \"Hello\"

Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.

Practical Example: Applying It in a Program

<?php

$messages = ["It's ready", "He said 'go'"];
foreach ($messages as $message) { echo addslashes($message) . PHP_EOL; }

Output:

It\'s ready
He said \"go\"

Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.

Important Behavior and Edge Cases

  • Key behavior: Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
  • Environment: Available in standard PHP.

Comparison With Related Functions

FunctionPurpose
addslashes()prefixes certain characters such as quotes and backslashes with a backslash.
htmlspecialchars()htmlspecialchars() encodes special HTML characters for output; addslashes() is not HTML or SQL escaping.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: Do not use addslashes() to make SQL statements safeDo not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.

Key Takeaways

  • prefixes certain characters such as quotes and backslashes with a backslash.
  • Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.
  • Available in standard PHP.

Summary: Do not use addslashes() to make SQL statements safe. Use prepared statements and htmlspecialchars() for HTML output.

Share this resourceSend this page to someone who may find it useful.