[英]Replace a repeating pattern using regex
I want to replace all non quoted array keys in my source code : 我想在源代码中替换所有未引用的数组键:
$array[keyValue]
with quoted array keys: 引用的数组键:
$array['keyValue']
For single dimension arrays this regexp allows me to do this : 对于单维数组,这个正则表达式允许我这样做:
preg_replace('/\$([a-z-_0-9]+)(\[([a-z][a-zA-Z-_0-9]+)\])+/', '\$$1['$3']', $input_lines);
test : https://www.phpliveregex.com/p/pXc 测试: https : //www.phpliveregex.com/p/pXc
Note all my keys start with a lower case letter. 请注意我的所有键都以小写字母开头。
My problem comes when I have multi dimension arrays and I want to change: 当我有多维数组并且我想要改变时,我的问题出现了:
$array[keyValue1][keyValue2]
to : 至 :
$array['keyValue1']['keyValue2']
or even 甚至
$array[keyValue1]...[keyValueN]
to 至
$array['keyValue1']...['keyValueN']
for larger dimension-ed arrays. 对于较大尺寸的数组。 Any attempt I make to match the pattern multiple times ends up matching between the first opening bracket
[
and the last one ]
as one match. 我做多次匹配模式的尝试最终在第一个开口括号
[
和最后一个]
匹配作为一个匹配。
Edit: Reason for doing this is to avoid errors and notices like this 编辑:执行此操作的原因是为了避免错误和通知
E_NOTICE : type 8 -- Use of undefined constant key - assumed 'key' -- at line 2
in my logs 在我的日志中
Note: take care of predefined constants. 注意:注意预定义的常量。 This doesn't and can't ignore them.
这不会也不能忽略它们。
You are in need of a continuous match using \\G
. 您需要使用
\\G
进行连续匹配。 Use preg_replace
with the following regex: 将
preg_replace
与以下正则表达式一起使用:
(\$\w+\[|\G(?!\A)\[)([^]['"]+)\]
and put the following string as the substitution string: 并将以下字符串作为替换字符串:
$1'$2']
See live demo here 在这里查看现场演示
PHP code: PHP代码:
preg_replace('~(\$\w+\[|\G(?!\A)\[)([^][\'"]+)\]~', '$1\'$2\']', $str);
Regex break down: 正则表达式崩溃:
(
Start of capturing group #1 (
开始捕获组#1
\\$\\w+\\[
Match a $
then some word characters then an opening bracket \\$\\w+\\[
匹配$
然后是一些单词字符然后是一个左括号 |
Or \\G(?!\\A)
Start match from where previous match ends \\G(?!\\A)
从上一场比赛结束的地方开始比赛 \\[
Match an opening bracket \\[
匹配一个开口括号 )
End of capturing group #1 )
捕获组#1结束 (
Start of capturing group #2 (
开始捕获组#2
[^]['"]+
Match anything but [
, ]
, '
and "
[^]['"]+
匹配[
, ]
, '
和"
)
End of capturing group #2 )
捕获组#2结束 \\]
Match a closing bracket \\]
匹配一个结束括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.