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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据