Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

php

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?

like image 805
Tim Avatar asked Apr 10 '11 11:04

Tim


People also ask

What does add slashes do in PHP?

The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: single quote (') double quote (")

Does PHP Use single or double quotes?

In PHP, people use single quote to define a constant string, like 'a' , 'my name' , 'abc xyz' , while using double quote to define a string contain identifier like "a $b $c $d" .

How do I strip a quote in PHP?

Try this: str_replace('"', "", $string); str_replace("'", "", $string); Otherwise, go for some regex, this will work for html quotes for example: preg_replace("/<!


1 Answers

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) . '"'; } 
like image 178
Gumbo Avatar answered Nov 09 '22 01:11

Gumbo