开发者

How to extract two variables from this string in PHP

I have a string like this :

oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc

How can I extract the two variables oauth_token and oauth_token_secret from the a开发者_运维知识库bout string using PHP

NOTE: this is not coming from the URL( we can do that using $_GET)

Thank YOU


Use parse_str() for parsing query string parameters.

// Extract into current scope, access as if they were PHP variables
parse_str($str);
echo $oauth_token;
echo $oauth_token_secret;

// Extract into array
parse_str($str, $params);
echo $params['oauth_token'];
echo $params['oauth_token_secret'];

You may wish to urldecode() the variables after you've extracted them.


try this

$text = "oauth_token=1%2F7VDUGD4tKIqSu4jX4DoeCRD1KbqqgTxFnFFliVgbSss&oauth_token_secret=Rk%2FwejMIg6t%2BFphvRd%2BZ5Wkc"
;
$i=explode('&',$text);
$j=explode('=',$i[0]);
$k=explode('=',$i[1]);
echo $j[0]."<br>";
echo $j[1]."<br>";
echo $k[0]."<br>";
echo $k[1]."<br>";


1, split the two parts of the $string,

$str_array = explode('&',$string);

2, get the part after the "=" sign, so for the oauth_token part:

 $oauth_token_array = explode('=',$str_array[0]);
 $oauth_token = $oauth_token_array[1];

EDIT: ignore this, it's definitely verbose. BoltClock's the solution.


The best way (most reusable) is to use a function which returns an array similar to $_GET.

edit There is already a function for this: http://www.php.net/manual/en/function.parse-str.php This will work with array get values too.

$values = array(); parse_str($query_strng, $values);

Quite an ugly function, why can't it just return the array of values. It either stuffs them into individual variables or you need to pass in a reference. Come on php, you can do better. /rant

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜