38

I am generating JSON with PHP.

I have been using

$string = 'This string has "double quotes"';

echo addslashes($string);

outputs: This string has \" double quotes\"

Perfectly valid JSON

Unfortunately addslashes also escapes single quotes with catastrophic results for valid JSON

$string = "This string has 'single quotes'";

echo addslashes($string);

outputs: This string has \'single quotes\'

In short, is there a way to only escape double quotes?

1

4 Answers 4

62

Although you should use json_encode if it’s available to you, you could also use addcslashes to add \ only to certain characters like:

addcslashes($str, '"\\/')

You could also use a regular expression based replacement:

function json_string_encode($str) {
    $callback = function($match) {
        if ($match[0] === '\\') {
            return $match[0];
        } else {
            $printable = array('"' => '"', '\\' => '\\', "\b" => 'b', "\f" => 'f', "\n" => 'n', "\r" => 'r', "\t" => 't');
            return isset($printable[$match[0]])
                   ? '\\'.$printable[$match[0]]
                   : '\\u'.strtoupper(current(unpack('H*', mb_convert_encoding($match[0], 'UCS-2BE', 'UTF-8'))));
        }
    };
    return '"' . preg_replace_callback('/\\.|[^\x{20}-\x{21}\x{23}-\x{5B}\x{5D}-\x{10FFFF}/u', $callback, $str) . '"';
}
0
21

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

There is no function like addslashes() that only adds a slash to double quotes.

However you can make use of addcslashes() to only add slashes to specific characters, e.g. only to double quotes:

addcslashes($string, '"');

That does exactly as described. If you want to have it compatible with stripcslashes() however, you need to add the slash itself to the list of chars:

addcslashes($string, '"\\');

That should do the job you've been asking for. I have no idea if that is compatible with json encoding.

5

If you are generating JSON, why not just use the json_encode() function ?

4
  • 7
    If the persone didn't know about this function and it solves his problem it is in the scope of the question.
    – koen
    Apr 10, 2011 at 11:40
  • @koen Exactly. Plus he also asked "In short, is there a way to only escape double quotes?" Apr 10, 2011 at 11:43
  • Thanks. Yes unfortunately json_encode was not applicable to this situation.
    – Tim
    Apr 10, 2011 at 11:46
  • json_encode() will fail for certain character combinations, like "\'". You will get a parse error. You can use addcslashes before to escape sequences like that.
    – Robse
    May 7, 2014 at 11:13
2
function json_string_encode( $str ) {
   $from = array('"');    // Array of values to replace
   $to = array('\\"');    // Array of values to replace with

   // Replace the string passed
   return str_replace( $from, $to, $str );
}

To use the function you simply need to use

$text = json_string_encode($text);
1
  • Thanks for posting an answer! While a code snippet could answer the question it's still great to add some addition information around, like explain, etc ..
    – j0k
    Oct 5, 2012 at 15:21

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.