开发者

How to 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 everything. By example, the functions that i need :

$thename=getvar($开发者_StackOverflow中文版vars,"name");
$theage=getvar($vars,"age");
$newvars=cleanup($vars,"name,age"); // Output $vars="name=david&age=26"

How can i get only the variables that i need . And how i clean up the $vars from the other variables if possible?

Thanks


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")));


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 is a working example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜