tags:

views:

119

answers:

4

My string is like the following format:

$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";

I want to split the string like the following:

$str[0] = "name=xxx&id=11";

$str[1] = "name=yyy&id=12";

$str[2] = "name=zzz&id=13";

$str[3] = "name=aaa&id=10";

how can I do this in PHP ?

+8  A: 

Try this:

$matches = array();
preg_match_all("/(name=[a-zA-Z0-9%_-]+&id=[0-9]+)/",$string,$matches);

$matches is now an array with the strings you wanted.

Update

function get_keys_and_values($string /* i.e. name=yyy&id=10 */) {
  $return = array();
  $key_values = split("&",$string);
  foreach ($key_values as $key_value) {
    $kv_split = split("=",$key_value);
    $return[$kv_split[0]] = urldecode($kv_split[1]);
  }
  return $return;
}
jigfox
+1 another beautiful example of why regular expression is the greatest flavor of noodle soup.
Gabriel
You should also use `urldecode()` to decode the variables after you parse them.
Lèse majesté
@Lèse majesté: your right. I will add an example for this.
jigfox
+3  A: 
$string = "name=xxx&id=11&name=yyy&id=12&name=zzz&id=13&name=aaa&id=10";
$arr = split("name=", $string);

$strings = aray();
for($i = 1; $i < count($arr), $i++){
    $strings[$i-1] = "name=".substr($arr[$i],0,-1);
}

The results will be in $strings

Thariama
+3  A: 

I will suggest using much simpler term

Here is an example

$string = "name=xxx&id=11;name=yyy&id=12;name=zzz&id=13;name=aaa&id=10";
$arr = explode(";",$string); //here is your array
Starx
won't work if he wants to split parameters of an already defined url
Thariama
@Thariama, then OP would ask regarding URL not string
Starx
depends. he then should have asked for an url, but some users mean "url" when they say "string"
Thariama
A: 

If you want to do what you asked, nothing more or less , that's explode('&', $string).

If you have botched up your example and you have a HTTP query string then you want to look at parse_str().

chx
this won't work because of duplicate strings like `name` and `id`
jigfox