8

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

color:red
material:metal

to an array like this

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

any idea?

0

3 Answers 3

17

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]);
2
  • Don't forget to at least strip out the possible "\r" from $cValue.
    – Jon
    Dec 2, 2010 at 14:32
  • @Jon Quite right, amended with that alteration and a regexp version which is quite pleasant.
    – Orbling
    Dec 2, 2010 at 15:23
2

Try this

$value = '1|a,2|b,3|c,4|d';
$temp = explode (',',$value);
foreach ($temp as $pair) 
{
    list ($k,$v) = explode ('|',$pair);
    $pairs[$k] = $v;
}

print_r($pairs);
1

explode first on line break. Prolly \n

Then explode each of the resulting array's items on : and set a new array to that key/value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.