【问题标题】:Convert string (similar json format) to object or array将字符串(类似json格式)转换为对象或数组
【发布时间】:2012-05-20 21:55:57
【问题描述】:

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

String '{"success": "false"....}' 可能会被json_decode转换成对象,但是我有没有qoutes的字符串。

【问题讨论】:

    标签: php curl double quotes


    【解决方案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;
    }
    

    试试这个,而不是正则表达式

    【讨论】:

    • 几乎可以工作了!在 regex string = {"success": "false", "errors": { "reason": '"�"�"�"�"вини�"�"е", "но"'}} 之后。字符串包括西里尔符号和单引号
    • 太好了,我已将标志添加到我的答案中
    • 我发现另一个问题,当string = {success: true, message: { header: 'reg', text: "\u0412\u044b \u0443\u0441\u043f\u0435\"}} 在正则表达式string = {"success": "true", "message": { "header": "reg", "text": "\"u0412"\"u044b"&amp;"nbsp";\"u0443"\"u0441"...}}之后
    • 我真的不知道如何解决这个问题,它已经是一个相当复杂的正则表达式。有没有办法更改接收字符串的来源以在其中添加引号?
    • 我无法更改源代码,但 CURL 可能发生了一些变化? ...curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_HEADER, 0);...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 2018-11-04
    • 1970-01-01
    • 2019-02-23
    • 2016-06-03
    • 2012-05-08
    • 2013-07-14
    相关资源
    最近更新 更多