如何在PHP中正确将代码字符串的array()语法替换为短数组[]语法
方案1:使用PHP内置Tokenizer解析(推荐,准确率100%)
PHP自带的token_get_all()函数可以把PHP代码解析为合法的语法令牌,能精准识别array关键字对应的数组声明,完全不会误判函数调用、字符串中的相关字符,适配任意嵌套层级的数组场景。
function replaceArrayToShortSyntax(string $code): string { $tokens = token_get_all($code); $output = ''; $arrayStack = []; foreach ($tokens as $token) { if (is_array($token)) { // 匹配数组声明用的array关键字,排除类名、方法名等其他场景的array字符串 if ($token[0] === T_ARRAY && ltrim($token[1]) === 'array') { $arrayStack[] = true; // 跳过array关键字,后续直接替换左括号为[ continue; } $output .= $token[1]; } else { // 左括号紧跟array关键字的情况,替换为[ if ($token === '(' && !empty($arrayStack)) { $output .= '['; continue; } // 匹配当前array对应的闭合右括号,替换为] if ($token === ')' && !empty($arrayStack)) { array_pop($arrayStack); $output .= ']'; continue; } $output .= $token; } } return $output; } // 测试用例 $testCode = '$my_variable = array(\'mykey\' => \'myvalue\', \'children\' => array(\'some value\', \'oh and sure another value\', \'childvalues\' => get_child_values()));'; echo replaceArrayToShortSyntax($testCode);
运行后输出结果和你预期的完全一致。
方案2:正则平衡组方案(适合无复杂字符串/注释的简单场景)
如果你的待处理代码没有在字符串、注释中包含array(这类特殊内容,可以用PCRE平衡组正则快速实现,写法更简洁:
$pattern = '/array\((?:[^()]|(?R))*\)/'; $output = preg_replace_callback($pattern, function($matches) { return '[' . substr($matches[0], 6, -1) . ']'; }, $testCode);
该方案的缺点是无法识别字符串、注释中的无关array(字符,可能出现误替换,复杂场景优先使用第一种方案。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

