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 maccms影视模板 制作影视网站失败 求
  • ¥15 stm32按键设置闹钟数进退位不正常
  • ¥15 三电平逆变器中点电位平衡问题
  • ¥20 这怎么写啊 java课设
  • ¥15 用C语言完成一个复杂的游戏
  • ¥15 如何批量更改很多个文件夹里的文件名中包含文件夹名?
  • ¥50 MTK手机模拟HID鼠标出现卡顿
  • ¥20 求下下面这个数据结构代码
  • ¥20 前端 二进制文件流图片转化异常
  • ¥15 github上的这个C语言项目如何跑起来