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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!