June 21, 2010
Parsing a string in PHP
Question by ungalnanban
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 ?
Answer by jigfox
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;
}
Answer by Starx
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