正则表达式用一种模式替换递归

时间:2015-08-23 20:20:46

标签: php arrays regex

$array[key][key]...[key] 替换为 $array['key']['key']...['key']

我设法只为数组的第一个关键字添加引号。

\$([a-zA-Z0-9]+)\[([a-zA-Z_-]+[0-9]*)\]替换为\$\1\[\'\2\3\'\]

2 个答案:

答案 0 :(得分:1)

您可以使用不执行递归连续匹配的正则表达式:

containment

请参阅IDEONE demo

正则表达式//Access the resize function of containment $(".box").resizable('instance').plugins.resize[0][1] = function (event) { ... //This is the only change to the original function. //It looks at the direction of the resize. //If axis is left or top then the calculations are made with position //instead of width, with an adjusment based on grid size if ((/w/.test(that.axis) ? that.position.left - 10 : woset) + that.size.width >= that.parentData.width) { that.size.width = that.parentData.width - woset; if (pRatio) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } } if ((/n/.test(that.axis) ? that.position.top - 10 : hoset) + that.size.height >= that.parentData.height) { that.size.height = that.parentData.height - hoset; if (pRatio) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } } ... } 匹配所有方括号子串(将其内容捕获到第2组)(使用$re = '/(\$\w+|(?!^)\G)\[([^]]*)\]/'; $str = "\$array[key][key][key]"; $subst = "$1['$2']"; $result = preg_replace($re, $subst, $str); echo $result; ),它们位于(\$\w+|(?!^)\G)\[([^]]*)\]子字符串之后(由于{{1}连续地跟随彼此(感谢\[([^]]*)\])。

答案 1 :(得分:1)

不需要任何花哨的东西,只需得到你需要的东西 替换回调。

未测试:

$new_input = preg_replace_callback('/(?i)\$[a-z]+\K(?:\[[^\[\]]*\])+/',
        function( $matches ){
             return preg_replace( '/(\[)|(\])/', "$1'$2", $matches[0]);
        },
        $input );