【问题标题】:How to extract two variables from this string in PHP如何在 PHP 中从这个字符串中提取两个变量
【发布时间】:2010-12-18 06:34:00
【问题描述】:

我有一个这样的字符串:

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

如何使用 PHP 从 about 字符串中提取两个变量 oauth_tokenoauth_token_secret

注意:这不是来自 URL(我们可以使用 $_GET 做到这一点)

谢谢你

【问题讨论】:

  • 你是在说 substr(myString, strpos(mystring, "="), strpos(mystring, "&") - strpos(mystring, "=")) 之类的事情

标签: php extract


【解决方案1】:

使用parse_str()解析查询字符串参数。

// 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'];

您可能希望在提取变量后urldecode()

【讨论】:

  • 这看起来很简单,但没有显示任何内容......你能纠正它吗?谢谢
  • @KillerFish:它为我输出了两个变量。
【解决方案2】:

试试这个

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

【讨论】:

    【解决方案3】:

    1、拆分$string的两部分,

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

    2、获取“=”号后面的部分,所以对于oauth_token部分:

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

    编辑:忽略这一点,这绝对是冗长的。 BoltClock 是解决方案。

    【讨论】:

      【解决方案4】:

      最好的方法(最可重用)是使用返回类似于 $_GET 的数组的函数。

      edit 已经有一个函数:http://www.php.net/manual/en/function.parse-str.php 这也适用于数组获取值。

      $values = 数组(); parse_str($query_strng, $values);

      相当丑陋的函数,为什么不能只返回值数组。它要么将它们填充到单独的变量中,要么您需要传入一个引用。来吧php,你可以做得更好。 /咆哮

      【讨论】:

      • 哈哈,我一直讨厌数组函数的这种不一致。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      相关资源
      最近更新 更多