【问题标题】:How to surround numbers with double quotes in php preg_replace?如何在 php preg_replace 中用双引号括起数字?
【发布时间】:2018-12-06 08:23:22
【问题描述】:

我有一个似乎无效的 json

{
        "systemId": 4424, 
        "professional":88928, 
        "gate":532, 
        "mock":02,
        "wish":"this", 
        "transaction_id":"eeases-323fasfse-asdfe33", 
        "channel": "API", 
    }

因此,它无法转换为 php 中的数组,我尝试了 json lint,它在 02 处显示错误。

经过一番研究,我知道json中从0开始的值是无效的。

当我用双引号“”将 02 括起来时,它已成功使用 json_decode 转换为数组。

所以我想知道,如何在所有假设 json 为字符串的情况下添加引号。

【问题讨论】:

  • 你还有一个额外的逗号在末尾"channel": "API", 。所以恕我直言,最好尝试修复源而不是破解结果。
  • 试试$s = preg_replace('~":\s*\K0+(?=[1-9]\d*,)~', '', $s)。不过,正则表达式方法可能并不安全。
  • 你想preg_replace这个无效值吗?你会生成 JSON 文件吗?如果是这样,我会修复生成 JSON 的代码
  • 02 with ["" was] successfully converted, how can I add quotes to [all numbers] 你确定能把你带到你想要的地方吗?
  • 嗨@greybeard,是的,我知道“”在 02 左右就足够了,但我不想要具体案例的答案,我愿意学习新的东西。

标签: php arrays json string preg-replace


【解决方案1】:
<?php
$data = '{
        "systemId":4424, 
        "professional":88928, 
        "gate":532, 
        "mock":02,
        "wish":"this", 
        "transaction_id":"eeases-323fasfse-asdfe33", 
        "channel": "API",
    }';


$data = str_replace('}', '', str_replace('{', '', $data));

echo '<pre>';


$t = preg_match_all("/(?<=\:)(.*?)(?=\,)/", $data, $matches);


$i=0;
foreach($matches[1] as $key => $value){
    if(is_numeric($value)){
        $matches[1][$i] = '"'.$value .'"';
    }
    $data = str_replace($value, $matches[1][$i], $data);
    $i++;
}

$data = rtrim(trim($data),','); //remove last comma


$data = '{'.$data .'}';

$data = json_decode($data,true);

print_r($data);

肮脏的解决方案,我 100% 同意在您得到响应之前“修复”您的 json 的想法。

如果您真的必须采用这种方式来修复代码中的 json,那么上面的代码将帮助您。

我首先修剪大括号的原因是为了让数据字符串更清晰。当我完成所有需要做的事情后,我将它们以最终格式连接起来。

代码的结果是:

Array
(
    [systemId] => 4424
    [professional] => 88928
    [gate] => 532
    [mock] => 02
    [wish] => this
    [transaction_id] => eeases-323fasfse-asdfe33
    [channel] => API
)

从有效 json 解码的数组

【讨论】:

  • 非常感谢您的努力。会尝试 100%!
  • 不客气,希望您的问题得到解决。让我知道进展如何。
  • 嗨@pr1nc3,我得到 {"systemId":" 4424", "professional":"88928", "gate":"532", "mock":"02", "wish" :"this", "transaction_id":"eeases-323fasfse-asdfe33", "channel": "API",} 在 json_decode 之前,但在 json_decode 之后什么都没有
  • 奇怪的是,我使用您提供的完全相同的“json”并且工作正常。你确定你没有修改任何代码,因为即使我在我的代码中修剪它,我仍然可以看到最后一个字段中的逗号。最后一个逗号会破坏您的 json 并使其无效,因此无法解码为数组。确保您没有删除我的 rtrim 函数。
  • 是的,逗号是问题所在,完成!谢谢
猜你喜欢
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-29
  • 2021-10-22
  • 2014-01-13
相关资源
最近更新 更多