[英]Regex replace recursive with one pattern
$array[key][key]...[key]
replace to $array['key']['key']...['key']
$array[key][key]...[key]
替换为$array['key']['key']...['key']
I managed only to add quotes to the first keyword of the array. 我设法只将引号添加到数组的第一个关键字。
\\$([a-zA-Z0-9]+)\\[([a-zA-Z_-]+[0-9]*)\\]
replace to \\$\\1\\[\\'\\2\\3\\'\\]
\\$([a-zA-Z0-9]+)\\[([a-zA-Z_-]+[0-9]*)\\]
替换为\\$\\1\\[\\'\\2\\3\\'\\]
You may use a regex that does not perform a recursive , but consecutive matching: 您可以使用不执行递归但连续匹配的正则表达式:
$re = '/(\$\w+|(?!^)\G)\[([^]]*)\]/';
$str = "\$array[key][key][key]";
$subst = "$1['$2']";
$result = preg_replace($re, $subst, $str);
echo $result;
See IDEONE demo 见IDEONE演示
The regex (\\$\\w+|(?!^)\\G)\\[([^]]*)\\]
matches all square parenthetical substrings (capturing their contents into Group 2) (with \\[([^]]*)\\]
) that either are right after a '$'+alphanumerics
substring (due to the \\$\\w+
part) or that follow one another consecutively (thanks to (?!^)\\G
). 正则表达式
(\\$\\w+|(?!^)\\G)\\[([^]]*)\\]
匹配所有方括号子串(将其内容捕获到组2中)(带有\\[([^]]*)\\]
)要么紧跟在'$'+alphanumerics
子字符串之后(由于\\$\\w+
部分),要么紧随其后(由于(?!^)\\G
)。
Shouldn't need anything fancy, just get the stuff you need then 不需要任何花哨的东西,只要拿到您需要的东西,然后
replace in a callback. 替换为回调。
Untested: 未经测试:
$new_input = preg_replace_callback('/(?i)\$[a-z]+\K(?:\[[^\[\]]*\])+/',
function( $matches ){
return preg_replace( '/(\[)|(\])/', "$1'$2", $matches[0]);
},
$input );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.