phpquery-stringstring-parsing

Parse improperly formatted URL querystring which is missing [] for repeated keys


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?


Solution

  • 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;
    }