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 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题