PHP中从动态字符串提取括号键值生成目标数组的方法
实现字符串转指定关联数组的方法
针对字符串 (parent)item category(child)master data(name)category,可以通过正则匹配结合数组处理得到目标关联数组,以PHP为例:
用正则表达式匹配键值对
使用正则\((.*?)\)(.*?)(?=\(|$)分别捕获括号内的键,以及括号后到下一个括号(或字符串结尾)的对应值。代码实现
$targetStr = "(parent)item category(child)master data(name)category"; // 匹配所有键值对 preg_match_all('/\((.*?)\)(.*?)(?=\(|$)/', $targetStr, $matches); // 合并键数组和值数组为关联数组 $resultArray = array_combine($matches[1], $matches[2]); // 输出结果 print_r($resultArray);
执行后会得到:
Array ( [parent] => item category [child] => master data [name] => category )
正则说明
\((.*?)\):非贪婪匹配括号内的内容,作为数组的键;(.*?)(?=\(|$):非贪婪匹配括号后的内容,直到遇到下一个括号或字符串结束,作为对应键值,正向预查(?=\(|$)确保不会多取内容。
内容的提问来源于stack exchange,提问作者hirohito
相关产品推荐
相关产品推荐

