简体   繁体   中英

PHP json encoded string escaping

I need to escape json encoded string.

I have encode below string.

json_encode(['test1' => '','test2' => '','test3' => ''])

It will store in mysql table like,

"{\"test1\":\"\",\"test2\":\"\",\"test3\":\"\"}"

I want to store like,

{"test":"","test2":"","test3":""}

Thank you !

Try below code

<?php
$json = json_encode(['test1' => '','test2' => '','test3' => '']);
$dbjson = "{\"title\":\"\",\"description\":\"\",\"keywords\":\"\"}";

echo "<pre>";
$value = json_encode(json_decode($dbjson));
print_r($value); // output : {"title":"","description":"","keywords":""}
?>

Add JSON_UNESCAPED_SLASHES as last argument

echo json_encode(['test1' => '','test2' => '','test3' => ''],JSON_UNESCAPED_SLASHES)

Output

{"test1":"","test2":"","test3":""}

You can use stripslashes function

$string = '{\"title\":\"\",\"description\":\"\",\"keywords\":\"\"}';
echo stripslashes($string);

And also you can Use preg_replace

<?php
 $string = '{\"title\":\"\",\"description\":\"\",\"keywords\":\"\"}';
 echo $new_str = preg_replace('~[\\\\/*?<>|]~', '', $string);
?>

Output :

{ "title ": "", "description ": "", "keywords ": ""}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM