如何从字符串中提取特定变量?

时间:2010-04-29 01:30:44

标签: php string variables

让我说我有以下内容:

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

我想把它变成真正的php变量而不是一切。例如,我需要的功能:

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

我怎样才能获得我需要的变量。如果可能的话,我如何从其他变量中清理$ vars?

由于

2 个答案:

答案 0 :(得分:8)

我会使用parse_str()然后操纵数组。

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

答案 1 :(得分:3)

您可以执行以下操作:

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

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.