字串處理成數組的有關問題

來源:互聯網
上載者:User
字串處理成數組的問題
一個字串如下:
$str = "aa:1,bb:2,cc:3,dd:4";


有兩個要求:

1、我想把這個字串拆分成一個數組,其中 aa、bb、cc、dd 為索引 11,22,33,44 分別為索引的值 如$arr = Array ( [aa] => 11, [bb] => 22, [cc] => 33, [dd] => 44 ) ,要怎麼弄

2、要把這個字串拆分成4個變數,變數名動態產生為 aa、bb、cc、dd 分別對應值為 11,22,33,44 這個要怎麼操作?

------解決方案--------------------
兩種方法:
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);
------解決方案--------------------
再來二種
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);
------解決方案--------------------
添塊磚

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)*/
------解決方案--------------------
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  
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.