如果找到两个连续的实例,则删除方括号的实例

时间:2017-08-01 06:44:10

标签: php regex preg-replace

我有以下方式的数据:

{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }

现在,如果有两个连续的实例,例如[],我想删除方括号的实例,即[ [] ]

现在,如果您看到上述数据,则可以看到有[]的实例连续重复两次。所以我想删除每个的一个实例。

现在,我可以检查每个连续重复的两个实例,并删除一个,如此

$text = '{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';

echo preg_replace('/\[ \[+/', '[', $text);

现在,上面的代码适用于[。因此,要删除连续重复的]实例,我必须再次重复相同的代码。

我想知道,有没有更好的方法来实现相同的结果。与此同时,我可以解决这个问题,但是如果将来我还要为其他角色做同样的事情呢?请在这里指导我。

2 个答案:

答案 0 :(得分:4)

您正在处理json字符串。禁止尝试字符串操作(使用正则表达式或其他方法),因为过度匹配"存在很多可能存在的缺陷。

虽然我不完全理解您的数据结构的可变性,但我可以通过将您的json字符串转换为数组然后使用数组函数安全地修改数据来提供一些临时指导。

考虑一下:

代码:(Demo

$json='{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';
$array=json_decode($json,true);  // convert to array
foreach($array as &$a){  // $a is modifiable by reference
    if(is_array($a) && isset($a[0]) && isset($a[0][0])){  // check if array and if two consecutive/nested indexed subarrays
        $a=array_column($a,0); // effectively shift deeper subarray up one level
    }
}
$json=json_encode($array);
echo $json;

输出:

{"id":"sugarcrm","text":"sugarcrm","children":[{"id":"accounts","text":"accounts","children":[{"id":"id","text":"id"},{"id":"name","text":"name"}]}]}

就此而言,如果您知道双嵌套索引所在的位置,那么您可以在不循环(或通过引用修改)的情况下访问它们,如下所示:

$json='{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';
$array=json_decode($json,true);
$array['children']=array_column($array['children'],0);  // modify 2 known, nested, indexed subarrays
$json=json_encode($array);
echo $json;

答案 1 :(得分:-1)

怎么样:

echo str_replace(array('[ [', '] ]'), array('[', ']'), $text);