How do I extract specific variables from a string?

let's say I have the following:

$vars="name=david&age=26&sport=soccer&birth=1984";

      

I want to turn this into real php variables, but not all. For example, the functions I need are:

$thename=getvar($vars,"name");
$theage=getvar($vars,"age");
$newvars=cleanup($vars,"name,age"); // Output $vars="name=david&age=26"

      

How can I only get the variables I need. And how can I clear $ vars of other variables if possible?

thanks

+2


a source to share


2 answers


You can do something like:

function getvar($arr,$key) {
    // explode on &.
    $temp1 = explode('&',$arr);

    // iterate over each piece.
    foreach($temp1 as $k => $v) {
        // expolde again on =.
        $temp2 = explode('=',$v);

        // if you find key on LHS of = return wats on RHS.
        if($temp2[0] == $key)
            return $temp2[1];   
    }
    // key not found..return empty string.
    return '';
}

      

and



function cleanup($arr,$keys) {
    // split the keys string on comma.
    $key_arr = explode(',',$keys);

    // initilize the new array.
    $newarray = array();

    // for each key..call getvar function.
    foreach($key_arr as $key) {
        $newarray[] = $key.'='.getvar($arr,$key);
    }

    // join with & and return.
    return implode('&',$newarray);
}

      

Here's a working example.

+3


a source


I would use parse_str()

and then manipulate the array.



$vars="name=david&age=26&sport=soccer&birth=1984";
parse_str($vars, $varray);

$thename = $varray["name"];
$theage = $varray["age"];
$newvars = array_intersect_key($varray, 
    array_flip(explode(",","name,age")));

      

+8


a source







All Articles