explode two-item-list in array as key=>value

后端 未结 3 950
不知归路
不知归路 2021-02-06 05:12

I\'d like to explode a multi-line-string like this

color:red
material:metal

to an array like this

$array[\'color\']=red
$array[         


        
3条回答
  •  攒了一身酷
    2021-02-06 05:38

    Use explode(), you can use a regexp for it, but it's simple enough without the overhead.

    $data = array();
    foreach (explode("\n", $dataString) as $cLine) {
        list ($cKey, $cValue) = explode(':', $cLine, 2);
        $data[$cKey] = $cValue;
    }
    

    As mentioned in comments, if data is coming from a Windows/DOS environment it may well have CRLF newlines, adding the following line before the foreach() would resolve that.

    $dataString = str_replace("\r", "", $dataString); // remove possible \r characters
    

    The alternative with regexp can be quite pleasant using preg_match_all() and array_combine():

    $matches = array();
    preg_match_all('/^(.+?):(.+)$/m', $dataString, $matches);
    $data = array_combine($matches[1], $matches[2]);
    

提交回复
热议问题