Explode a list of two elements in an array as a key value =>

I would like to explode a multi-line string like this

color:red material:metal 

into an array like this

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

any idea?

+8
arrays php explode
source share
3 answers

Use explode () , you can use regexp for it, but it is simple enough without overhead.

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

As mentioned in the comments, if the data comes from a Windows / DOS environment, it may have CRLF lines, adding the following line before foreach() resolves this.

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

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

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

try it

 $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); 
+2
source share

explode first at line break. Prolly \ n

Then explode each of the resulting array elements on: and set a new array on this key / value.

+1
source share

Source: https://habr.com/ru/post/649755/


All Articles