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


i'd explode multi-line-string this

color:red material:metal 

to array this

$array['color']=red $array['material']=metal 

any idea?

use explode(), can use regexp it, it's simple enough without overhead.

$data = array(); foreach (explode("\n", $datastring) $cline) {     list ($ckey, $cvalue) = explode(':', $cline, 2);     $data[$ckey] = $cvalue; } 

as mentioned in comments, if data coming windows/dos environment may have crlf newlines, adding following line before foreach() resolve that.

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

the alternative regexp can quite pleasant using preg_match_all() , array_combine():

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

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -