将字符串(类似的json格式)转换为对象或数组

时间:2012-05-12 17:34:21

标签: php curl double quotes

我收到CURL的字符串“{success:false,errors:{reason:'text text text'}}”,如何将此字符串转换为数组或对象?

String'{“success”:“false”....}'可以通过json_decode转换为对象,但我有没有qoutes的字符串。

1 个答案:

答案 0 :(得分:1)

首先使用此正则表达式(它添加引号)

$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;
}

尝试使用而不是正则表达式

相关问题