Problems related to string processing into arrays

Source: Internet
Author: User
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 
        

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.