简体   繁体   English

PHP json编码的字符串转义

[英]PHP json encoded string escaping

I need to escape json encoded string. 我需要转义json编码的字符串。

I have encode below string. 我已经在字符串下面encode

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

It will store in mysql table like, 它将像这样存储在mysql表中,

"{\"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 JSON_UNESCAPED_SLASHES添加为最后一个参数

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

Output 产量

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

You can use stripslashes function 您可以使用stripslashes函数

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

And also you can Use preg_replace 你也可以使用preg_replace

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

Output : 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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