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

PHP提取数组元素括号内容并生成对应数组的实现问题

PHP数组提取括号内容并清理原元素的解决方案

原数组示例:

$originalArray = [
    0 => 'foo (bar1)',
    1 => 'bar (foo2)',
    2 => 'bas',
    3 => 'foo (bas3)',
    4 => 'bar'
];

需求:

  • 移除原数组中所有元素的括号及括号内内容
  • 生成新数组,原元素含括号的提取括号内文本,无括号的对应值为 ,且保持键名与原数组一致

解决方案

核心是遍历数组逐个处理元素——你之前用preg_match报错是因为直接传入了数组,它只能处理单个字符串;preg_grep仅能过滤元素,无法提取内容,所以必须循环处理每个项。

完整代码:

$originalArray = [
    0 => 'foo (bar1)',
    1 => 'bar (foo2)',
    2 => 'bas',
    3 => 'foo (bas3)',
    4 => 'bar'
];

$bracketContent = [];
$cleanedArray = [];

// 遍历原数组,保留原键名
foreach ($originalArray as $key => $value) {
    // 匹配括号及内部内容,非贪婪避免多括号场景出错
    if (preg_match('/\((.*?)\)/', $value, $matches)) {
        $bracketContent[$key] = $matches[1];
        // 移除括号部分并清理残留空格
        $cleanedArray[$key] = trim(str_replace($matches[0], '', $value));
    } else {
        $bracketContent[$key] = ' ';
        $cleanedArray[$key] = $value;
    }
}

// 输出结果
print_r($cleanedArray);
print_r($bracketContent);

结果说明

  • 清理后的原数组$cleanedArray:
Array
(
    [0] => foo
    [1] => bar
    [2] => bas
    [3] => foo
    [4] => bar
)
  • 提取的括号内容数组$bracketContent:
Array
(
    [0] => bar1
    [1] => foo2
    [2] =>  
    [3] => bas3
    [4] =>  
)

内容的提问来源于stack exchange,提问作者bear87

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:42:17