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

Ton*_*ana 0 php regex preg-replace

我有以下方式的数据:

{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }
Run Code Online (Sandbox Code Playgroud)

现在,我想删除括号,即实例[]是否有这样的两个连续的情况下,[ [] ]

现在,如果你看到上面的数据,你会在这里看到,有实例[]其连续两次重复。所以我想删除每个的一个实例。

现在,我可以检查每个的两个连续重复的实例并删除一个,就像这样

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

echo preg_replace('/\[ \[+/', '[', $text);
Run Code Online (Sandbox Code Playgroud)

现在,上面的代码是为[. 因此,要删除 的连续重复实例],我将不得不再次重复相同的代码。

我想知道,是否有更好的方法来实现相同的结果。同时,我可以解决这个问题,但如果将来我必须对任何其他角色做同样的事情怎么办?请在这里指导我。

mic*_*usa 5

您正在处理一个 json 字符串。尝试字符串操作(使用正则表达式或其他)是禁忌的,因为“过度匹配”很可能存在陷阱。

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

考虑一下:

代码:(演示

$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;
Run Code Online (Sandbox Code Playgroud)

输出:

{"id":"sugarcrm","text":"sugarcrm","children":[{"id":"accounts","text":"accounts","children":[{"id":"id","text":"id"},{"id":"name","text":"name"}]}]}
Run Code Online (Sandbox Code Playgroud)

就此而言,如果您知道双嵌套索引的位置,那么您可以像这样访问它们而无需循环(或通过引用修改):

$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;
Run Code Online (Sandbox Code Playgroud)