2010-04-29 8 views
2

Disons que je donne les résultats suivants:Comment extraire des variables spécifiques d'une chaîne?

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

Je veux transformer cela en php variables réelles, mais pas tout. Par exemple, les fonctions dont j'ai besoin:

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

Comment puis-je obtenir uniquement les variables dont j'ai besoin. Et comment puis-je nettoyer les variables $ des autres variables si possible?

Merci

Répondre

3

Vous pouvez faire quelque chose comme:

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

et

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

Merci beaucoup, c'est exactement ce que je cherche! – Ryan

8

J'utiliser parse_str() puis manipuler le tableau.

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

C'est bien aussi +1 – Ryan

+1

Ceci est une meilleure réponse – SeanJA

Questions connexes