The problem of string processing into an array: $ str & quot; aa: 1, bb: 2, cc: 3, dd: 4 & quot; has two requirements: 1. I want to split this string into an array, where aa, bb, cc, and dd are indexes 11, 22, and 33, and 44 are the index values, for example, $ arrArray ([aa] & gt; 11, [bb] & gt; 22, [cc] & gt string processing into an array
A string is as follows:
$ Str = "aa: 1, bb: 2, cc: 3, dd: 4 ";
There are two requirements:
1. I want to split this string into an array, where aa, bb, cc, and dd are indexes 11, 22, 33,44 are index values such as $ arr = Array ([aa] => 11, [bb] => 22, [cc] => 33, [dd] => 44). how can this problem be solved?
2. split the string into four variables. the variable names dynamically generate aa, bb, cc, and dd corresponding to values 11, 22, and 44 respectively. how can this problem be solved?
------ Solution --------------------
Two methods:
1,
PHP code
$ Str = "aa: 1, bb: 2, cc: 3, dd: 4"; parse_str (preg_replace (array ('/\ w + /','/: /','/,/'), array (' "$0" ',' = ',' & '), $ str), $ ar ); print_r ($ ar );
------ Solution --------------------
Two more types
PHP code
$ Str = "aa: 1, bb: 2, cc: 3, dd: 4"; foreach (array_chunk (preg_split ('/[:,]/', $ str ), 2) as $ t) $ ar [$ t [0] = $ t [1]; print_r ($ ar );
------ Solution --------------------
Add Bricks
PHP code
$ Str = "aa: 1, bb: 2, cc: 3, dd: 4"; preg_replace ("# ([\ w] +) :( [\ d] +) # e "," \ $ arr ['\ 1'] =\\ 2 \ 2 ", $ str); print_r ($ arr ); /* Array ([aa] => 11 [bb] => 22 [cc] => 33 [dd] => 44 )*/
------ Solution --------------------
PHP code
[User:root Time:14:14:44 Path:/home/liangdong/php]$ php arr.php 1234[User:root Time:14:14:45 Path:/home/liangdong/php]$ cat arr.php