Get array from string in pattern - key1:val1,val2,..;key2:va


Get array from string in pattern - key1:val1,val2,..;key2:val1,

我想从这样的字符串中得到

color:blue,red;size:s

到关联多数组

[
    color => [blue,red],
    size => [s]
]

我尝试了([a-z]+):([a-z^,]+),但这还不够;我不知道怎么递归

我不会在这种情况下使用正则表达式。可以多次使用explosion ()

<?php
$str = 'color:blue,red;size:s';
$values = explode(';', $str);
$arr = [];
foreach($values as $val) {
    $parts = explode(':', $val);
    $arr[$parts[0]] = explode(',', $parts[1]);
}
输出:

Array
(
    [color] => Array
        (
            [0] => blue
            [1] => red
        )
    [size] => Array
        (
            [0] => s
        )
)
$dataText   =   'color:blue,red;size:s';
$data   =   explode(';', $dataText);
$outputData =   [];
foreach ($data as $item){
    $itemData   =   explode(':', $item);
    $outputData[$itemData[0]]   =   explode(',', $itemData[1]);
}
print_r('<pre>');
print_r($outputData);
print_r('</pre>');

与regex不像爆炸那么简单,但你可以试试这个…

$re = '/('w+)':([^;]+)/';
$str = 'color:blue,red;size:s'; 
preg_match_all($re, $str, $matches);
// Print the entire match result 
$result = array();
$keys = array();
for($i = 1; $i < count($matches); $i++) {
    foreach($matches[$i] as $k => $val){
        if($i == 1) {
            $result[$val] = array();
            $keys[$k] = $val;
        } else {
            $result[$keys[$k]] = $val;
        }
    }
}
echo '<pre>';
print_r($result);
echo '</pre>';
结果

Array
(
    [color] => blue,red
    [size] => s
)