php字符串转化成数组

WBOY
Release: 2016-06-23 14:16:52
Original
918 people have browsed it

如下这段字符串:sex-1-area-2-pagesize-18-pageindex-1  转化成数组

[sex] => 1 [area] => 2 [pagesize] => 18 [pageinde] => 1

我用explode,只能 [0] => sex [1] => 1 [2] => area [3] => 2 这样的

上面的字符串是一个URL传递的参数


回复讨论(解决方案)

$s = 'sex-1-area-2-pagesize-18-pageindex-1';foreach(array_chunk(explode('-', $s), 2) as $v) {  $r[$v[0]] = $v[1];}print_r($r);
Copy after login
Array
(
[sex] => 1
[area] => 2
[pagesize] => 18
[pageindex] => 1
)

也可以用正则

$s = 'sex-1-area-2-pagesize-18-pageindex-1';preg_match_all('/(\w+)\-(\w+)/', $s, $r);$r = array_combine($r[1], $r[2]);print_r($r);
Copy after login
Array
(
[sex] => 1
[area] => 2
[pagesize] => 18
[pageindex] => 1
)

$test = "sex-1-area-2-pagesize-18-pageindex-1";	$preg = "/(?<=\d)-(?=[a-z])/";	$res = preg_split($preg,$test);		foreach($res as $tmp){		list($key,$value) = explode("-",$tmp);		echo $key."=>".$value;	}
Copy after login

<?php$str = 'sex-1-area-2-pagesize-18-pageindex-1';$str = explode('-', $str);for($i=0,$max=count($str);$i<$max;$i++) {	$result[$str[$i]] = $str[++$i];}print_r($result);
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template