在数组中查找缺少的尾随逗号

时间:2018-01-12 15:36:02

标签: php regex phpstorm

我会发现每个数组(PHP样式)

中每个缺少的逗号

找到这个

array(
    'example',
    'example'
);

并修复它们

array(
    'example',
    'example',
);

我会将正则表达式直接放在PhpStorm中,但我在线正则表达式的尝试不成功

注意:这不是.php文件,CTRL+ALT+L重新格式代码不起作用

我至少会找到它们,如果有提示也可以修复它们我会接受它!

更新

感谢@CD001提出的/array\([^\)]*\'\s*\);/gs近乎完美!

他的解决方案在此示例中失败

->setSomething(array(
    'example',
    'example'
));

这是 optionnal ,就像@CD001所说,这也提出了在结束'之前没有)标记的问题

样品

->setSomething(array(
    new Test,
    'example'
));

->setSomething(array
    'example',
    new Test
));

如果这里有一个正则表达式大师:) 此处还提供了一个代码段:https://regex101.com/r/aKfZC9/4/

2 个答案:

答案 0 :(得分:2)

我添加了一些额外的示例,并在您的示例中按@CD001扩展了正则表达式:https://regex101.com/r/ukPbft/1

假设您不希望匹配短数组语法并在函数调用中的任何位置匹配数组(意味着它不一定会跟随冒号),正则表达式将如下所示:

/array\((?!\s*\)+)[^\)]+(?<!,|,\s)\)/gs

但是对于PHPStorm,你需要这种格式:

array\((?!\s*\)+)[^\)]+(?<!,|,\s)\)
  

<强>解释

     

数组\( - 匹配开头'数组('标记。

     

(?!\ s * \)+) - 一个积极的先行,以确保数组不仅仅包含开始和结束括号之间的空格,因此它不匹配' array()'。

     

[^ \]] + - 确保在结束括号前至少有一个字符,因此它与'array()'不匹配

     

(?&lt;!,|,\ s) - 为了确保在数组末尾没有逗号空格,前面有逗号,这是一个负面的背后隐藏声明

     

\) - 匹配右括号

答案 1 :(得分:0)

你的第一个例子是正确的。第二个例子,php忽略了最后一个条目。

$x = array("example1","example2");
: array = 
  0: string = example1
  1: string = example2
$y = array("example1","example2",);
: array = 
  0: string = example1
  1: string = example2
$x1 = count($x);
: long = 2
$y1 = count($y);
: long = 2