我试图将字符串转换为数组,但是,当字符串包含括号中的项目时,我想创建多维数组.
例如,如果传递的字符串:(Mary Poppins)Umbrella(Color Yellow)
我想创建一个如下所示的数组:
Array ( [0] => Array ( [0] => mary [1] => poppins) [1] => umbrella [2] => Array ( [0] => color [1] => yellow) )
我能够通过以下方式将数据放入数组中:
preg_match_all('/\(([A-Za-z0-9 ]+?)\)/', stripslashes($_GET['q']), $subqueries);
但我无法将项目放在多维数组中.
有任何想法吗?
解决方法:
使用一些PHP-Fu:
$string = '(Mary Poppens) Umbrella (Color Yellow)';
$array = array();
preg_replace_callback('#\((.*?)\)|[^()]+#', function($m)use(&$array){
if(isset($m[1])){
$array[] = explode(' ', $m[1]);
}else{
$array[] = trim($m[0]);
}
}, $string);
print_r($array);
输出:
Array
(
[0] => Array
(
[0] => Mary
[1] => Poppens
)
[1] => Umbrella
[2] => Array
(
[0] => Color
[1] => Yellow
)
)
Note that you need PHP 5.3+ since I’m using an anonymous function.
兼容吗?
$string = '(Mary Poppens) Umbrella (Color Yellow)';
preg_match_all('#\((.*?)\)|[^()]+#', $string, $match, PREG_SET_ORDER);
foreach($match as $m){
if(isset($m[1])){
$array[] = explode(' ', $m[1]);
}else{
$array[] = trim($m[0]);
}
}
print_r($array);
Tested on PHP 4.3+