【发布时间】:2012-05-20 21:55:57
【问题描述】:
我通过 CURL 收到字符串“{success: false, errors: { reason: 'text text text' }}”,如何将此字符串转换为数组或对象?
String '{"success": "false"....}' 可能会被json_decode转换成对象,但是我有没有qoutes的字符串。
【问题讨论】:
我通过 CURL 收到字符串“{success: false, errors: { reason: 'text text text' }}”,如何将此字符串转换为数组或对象?
String '{"success": "false"....}' 可能会被json_decode转换成对象,但是我有没有qoutes的字符串。
【问题讨论】:
首先使用这个正则表达式(它添加引号)
$json = preg_replace ('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/u', '"$1"', $string);
之后,您可以简单地使用 json_decode()
$array = json_decode ($json);
我在某处找到了这个脚本:
function json_fix_quotes ($string){
$string = str_replace("{",'{"',$string);
$string = str_replace(":'",'":"',$string);
$string = str_replace("',",'","',$string);
$string = str_replace("'}",'"}',$string);
return $string;
}
试试这个,而不是正则表达式
【讨论】:
string = {success: true, message: { header: 'reg', text: "\u0412\u044b \u0443\u0441\u043f\u0435\"}} 在正则表达式string = {"success": "true", "message": { "header": "reg", "text": "\"u0412"\"u044b"&"nbsp";\"u0443"\"u0441"...}}之后
...curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_HEADER, 0);...