doushi3189 2017-08-23 11:18
浏览 143
已采纳

如何在php中用双引号和斜杠清理json字符串

I have problem with json string in php. I have an app the get user contacts and send it to server and I process contacts in my way.

the problem is that some contacts name are very wired and some error occurred while using json_decode() contacts like this

[
   {"displayName":"Altin"'''''"''''"""""
\""\p chapar","phoneNumbers":[{"value":"0411*******"}]},
   {"displayName":"A""""""basi","phoneNumbers":[{"value":"0914******"}]}
]

how can I clean this dirty json string to work properly? I've tried to remove """ and \\// but I saw a huge amount of errors

thanks

  • 写回答

1条回答 默认 最新

  • duanla8800 2017-08-23 12:19
    关注

    try this

        $result = str_split($contacts);
    
        for ($i = 0; $i < count($result); $i++)
        {
            $found = false;
    
            if ($result[$i] == '"')
            {
                if ($result[$i + 1] != ':' && $result[$i + 1] != ',' 
                    && $result[$i - 1] != '{' && $result[$i - 1] != '"' 
                        && $result[$i + 1] != '}' && $result[$i - 1] != ':' 
                            && $result[$i - 1] != ',')
                    $result[$i] = '';
            }
        }
    
        $edited = implode("", $result);
        $edited = str_replace("'" , '' , $edited);
        $edited = str_replace("\\" , '' , $edited);
        $edited = str_replace("
    " , '' , $edited);
        print_r(json_decode($edited));
    

    this will replace all inner double quotes so the string will be clean for the json_decode to produce std_objects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同