Is there a PHP function that only adds slashes to double quotes NOT single quotes

PHP doesn't have a built-in function that specifically adds slashes only to double quotes while ignoring single quotes. However, you can achieve this using str_replace() or create a custom solution with addcslashes().

Using str_replace()

The simplest approach is to use str_replace() to specifically target double quotes ?

<?php
$str = 'He said "Hello" and she replied "Hi!"';
$result = str_replace('"', '"', $str);
echo $result;
?>
He said "Hello" and she replied "Hi!"

Using addcslashes() for Double Quotes Only

The addcslashes() function can target specific characters. To escape only double quotes, specify the double quote character ?

<?php
$str = 'He said "Hello" and 'Goodbye' with "quotes"';
$result = addcslashes($str, '"');
echo $result;
?>
He said "Hello" and 'Goodbye' with "quotes"

Custom Function Example

You can create a reusable function for this specific requirement ?

<?php
function escapeDoubleQuotes($string) {
    return str_replace('"', '"', $string);
}

$text = 'John's book is titled "PHP Basics" and costs $25';
echo escapeDoubleQuotes($text);
?>
John's book is titled "PHP Basics" and costs $25

Comparison

Method Performance Flexibility
str_replace() Fast Simple, single character
addcslashes() Good Multiple characters possible

Conclusion

Use str_replace() for simple double quote escaping, or addcslashes() when you need more control over which characters to escape. Both methods preserve single quotes unchanged.

Updated on: 2026-03-15T08:49:51+05:30

680 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements