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

时间:2016-10-20 12:58:47

标签: php regex

I would like to get from a string like this

color:blue,red;size:s

to an associative multiarray

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

I tried with ([a-z]+):([a-z^,]+) but it's not enough; I don't know how to recursive it or something.

3 个答案:

答案 0 :(得分:3)

I wouldn't use regular expressions for something like this. Instead use explode() several times.

<?php

$str = 'color:blue,red;size:s';

$values = explode(';', $str);

$arr = [];
foreach($values as $val) {
    $parts = explode(':', $val);
    $arr[$parts[0]] = explode(',', $parts[1]);
}

Output:

Array
(
    [color] => Array
        (
            [0] => blue
            [1] => red
        )

    [size] => Array
        (
            [0] => s
        )

)

答案 1 :(得分:0)

$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>');

答案 2 :(得分:0)

With regex is not so simple like explode, but you can try this...

$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>';

result

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