问题:
我有一个看起来像这样的字符串:
[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]
问题:
你怎么能把那个字符串放进去?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
我会尝试:
$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]';
$output = array();
preg_match_all('\[(\d+)=>([\d,]+)\]', $input, $matches);
foreach ($matches as $group) {
$output[$group[1])] = explode(',', $group[2]);
}
// and print result out:
foreach ( $output as $key => $val ) {
echo $key . '<br/>';
foreach ( $val as $v ) {
echo ' ' . $v . '<br/>';
}
}
这段代码:
$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]';
$regex = '~\[(?P<keys>\d)+=>(?P<values>(?:\d+,?)+)\]~';
$result = array();
if (preg_match_all($regex, $input, $matches)) {
foreach ($matches['keys'] as $key => $value) {
$result[$value] = explode(',', $matches['values'][$key]);
}
}
print_r($result);
结果:
Array
(
[1] => Array
(
[0] => 2
[1] => 3
[2] => 4
)
[5] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[9] => Array
(
[0] => 10
[1] => 11
[2] => 12
)
[3] => Array
(
[0] => 14
[1] => 15
)
[6] => Array
(
[0] => 17
[1] => 18
)
)
$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]";
$str = explode("]", $str);
$finalResult = array();
foreach ($str as $element) {
if (!empty($element)) {
$element = substr($element, 1);
$element = explode("=>", $element);
// element[0] contains the key
$element[1] = explode(",", $element[1]);
$finalResult[$element[0]] = $element[1];
}
}
print_r($finalResult);
<?php
$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]";
$parts1 = explode("][",$str);
$parts1[0]=str_replace("[","",$parts1[0]);
$parts1[count($parts1)-1]=str_replace("]","",$parts1[count($parts1)-1]);
foreach($parts1 as $k=>$v){
$parts2[]=explode("=>",$v);
}
foreach($parts2 as $k=>$v){
echo "<div>".$v[0]."</div>";
foreach(explode(",",$v[1]) as $key=>$value){
echo "<div style='margin-left:20px'>".$value."</div>";
}
}
输出将是
仅使用str_replace()
:
$dict = array(
'=>' => "\n\t",
',' => "\n\t",
'][' => "\n",
'[' => '',
']' => '',
);
echo str_replace(array_keys($dict), array_values($dict), $str);
会给你想要的结果。