我需要使用PHP在数组中转换JSON字符串,但我需要转义双引号。
$string = '["label":"Name","type":"text","placeholder":"Mario","name":"name",*],
["label":"Email","type":"email","placeholder":"mail@example.com","name":"email",*],
["label":"Message","type":"textarea","value":"In this box you can insert a <a href="#" target="_blank">link</a>"]';
$jsonify = strip_tags($string,"<a>");
$jsonify = str_replace('*','"required":"required"',$jsonify);
$jsonify = str_replace('[','{',str_replace(']','}',$jsonify));
$jsonify = str_replace(array("\r\n", "\r"),"",$jsonify);
$jsonify = preg_replace("/\s+/", " ", $jsonify);
$jsonify = '['.jsonify.']';
echo $jsonify;
// OUTPUT IS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail@example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a <a href="#" target="_blank">link</a>"}]
// BUT IS NOT JSON VALID. IT SHOULD BE THIS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail@example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a <a href=\"#\" target=\"_blank\">link</a>"}]
如何获取有效的JSON字符串?
答案 0 :(得分:0)
你的字符串不是json有效的
这是$string
json有效
[
{
"label": "Name",
"type": "text",
"placeholder": "Mario",
"name": "name"
},
{
"label": "Email",
"type": "email",
"placeholder": "mail@example.com",
"name": "email"
},
{
"label": "Message",
"type": "textarea",
"value": "In this box you can insert a <a href='#' target='_blank'>link</a>"
}
]
测试一下,并删除其他代码strip_tags,Str_replace,preg_replace
echo json_encode($string);
答案 1 :(得分:0)
只需将数组/字符串传递给json_encode即可获得有效的json文件:
$array = array(
array("label" => "Name", "type" => "text", "placeholder" => "Mario", "name" => "name"),
array("label" => "Email", "type" => "email", "placeholder" => "mail@example.com", "name" => "email"),
array("label" => "Message", "type" => "textarea", "value" => "In this box you can insert a <a href='#' target='_blank'>link</a>")
);
$json = json_encode($array);
var_dump($json);