You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中从动态字符串提取括号键值生成目标数组的方法

实现字符串转指定关联数组的方法

针对字符串 (parent)item category(child)master data(name)category,可以通过正则匹配结合数组处理得到目标关联数组,以PHP为例:

  1. 用正则表达式匹配键值对
    使用正则 \((.*?)\)(.*?)(?=\(|$) 分别捕获括号内的键,以及括号后到下一个括号(或字符串结尾)的对应值。

  2. 代码实现

$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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:18:35