user381800
user381800

Reputation:

Parse and sanitize a (URL) querystring into an associative array

I need some help writing a code that creates an array in the format I needed in. I have this long string of text like this -> "settings=2&options=3&color=3&action=save"...etc Now the next thing I did to make it into an array is the following:

$form_data = explode("&", $form_data);

Ok so far so good...I now have an array like so:

Array
(
[0] => settings=2
[1] => options=3
[2] => color=3
[3] => action=save
)
1

Ok now I need to know how to do two things. First, how can I remove all occurences of "action=save" from the array?

Second, how can I make this array become a key value pair (associative array)? Like "settings=>2"?

Upvotes: 2

Views: 108

Answers (3)

deceze
deceze

Reputation: 522523

There's a function for that. :)

parse_str('settings=2&options=3&color=3&action=save', $arr);
if (isset($arr['action']) && $arr['action'] == 'save') {
    unset($arr['action']);
}
print_r($arr);

But just for reference, you could do it manually like this:

$str = 'settings=2&options=3&color=3&action=save';
$arr = array();
foreach (explode('&', $str) as $part) {
    list($key, $value) = explode('=', $part, 2);
    if ($key == 'action' && $value == 'save') {
        continue;
    }
    $arr[$key] = $value;
}

This is not quite equivalent to parse_str, since key[] keys wouldn't be parsed correctly. I'd be sufficient for your example though.

Upvotes: 3

codaddict
codaddict

Reputation: 455360

$str = 'settings=2&options=3&color=3&action=save&action=foo&bar=save';
parse_str($str, $array);
$key = array_search('save', $array);
if($key == 'action') {
        unset($array['action']);
}

Ideone Link

Upvotes: 1

TNC
TNC

Reputation: 5386

This could help on the parsing your array, into key/values

$array; // your array here
$new_array = array();

foreach($array as $key)
{
    $val = explode('=',$key);
    // could also unset($array['action']) if that's a global index you want removed
    // if so, no need to use the if/statement below - 
    // just the setting of the new_array  
    if(($val[0] != 'action' && $val[1] != 'save'))$new_array[] = array($val[0]=>$val[1]);
}

Upvotes: 0

Related Questions