可以通过正则表达式和字符串操作实现。
首先,我们可以使用正则表达式匹配括号内的数组,并将其提取出来。可以使用preg_match_all
函数来实现这一步骤。
$str = "abc (1,2,3) def (4,5,6) ghi (7,8,9)";
preg_match_all('/\((.*?)\)/', $str, $matches);
上述代码会将括号内的数组匹配到的结果存储在$matches
数组中。
接下来,我们可以使用循环遍历$matches
数组中的每一个匹配结果,并使用字符串操作函数拆分每个数组字符串为多维数组。
$result = array();
foreach ($matches[1] as $match) {
$arr = explode(",", $match);
$nestedArray = array();
foreach ($arr as $value) {
$nestedArray[] = trim($value);
}
$result[] = $nestedArray;
}
最后,我们得到了拆分后的多维数组$result
。
完整的PHP代码如下:
$str = "abc (1,2,3) def (4,5,6) ghi (7,8,9)";
preg_match_all('/\((.*?)\)/', $str, $matches);
$result = array();
foreach ($matches[1] as $match) {
$arr = explode(",", $match);
$nestedArray = array();
foreach ($arr as $value) {
$nestedArray[] = trim($value);
}
$result[] = $nestedArray;
}
print_r($result);
以上代码将输出:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
)
这样,我们成功将包含在括号内的数组拆分为了多维数组。
推荐的腾讯云相关产品和产品介绍链接地址如下:
注意:以上链接仅为示例,具体产品选择需要根据实际需求进行评估。
领取专属 10元无门槛券
手把手带您无忧上云