【问题标题】:Extract cookies data in header在标头中提取 cookie 数据
【发布时间】:2015-05-08 12:08:33
【问题描述】:

我有这个随机字符串。我只需要字符串中的特定文本,例如mcnb8h1apihg9ffav1ubtgal77Sat, 09-May-2015 11:49:58 GMT

$str = 'HTTP/1.1 302 Moved Temporarily Date: Fri, 08 May 2015 11:49:58 GMT Server: Apache/2.2.22 (Debian) X-Powered-By: PHP/5.5.23-1~dotdeb.1 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Set-Cookie: OSTSESSID=mcnb8h1apihg9ffav1ubtgal77; expires=Sat, 09-May-2015 11:49:58 GMT; Max-Age=86400; path=/support/; domain=myweb.com; secure Location: index.php Vary: Accept-Encoding Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 HTTP/1.1 200 OK Date: Fri, 08 May 2015 11:49:58 GMT Server: Apache/2.2.22 (Debian) X-Powered-By: PHP/5.5.23-1~dotdeb.1 Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache Set-Cookie: OSTSESSID=sugrlug6sj8m27lrkv5id9v473; expires=Sat, 09-May-2015 11:49:58 GMT; Max-Age=86400; path=/support/; domain=myweb.com; secure Vary: Accept-Encoding Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8';

这个字符串是完全随机的。我尝试通过以下方式解决它:

$pattern = "#OSTSESSID=(.*); expires=(.*)\n#";
preg_match_all($pattern, $str, $matches);

print_r($matches);

但不起作用。请帮我解决这个问题。

【问题讨论】:

  • $_COOKIE['OSTSESSID'] 不起作用的任何原因?

标签: php regex cookies http-headers preg-match-all


【解决方案1】:

您可能应该read up on Regex 以及您可以使用的各种运算符。

并使用https://regex101.com/ 作为排除故障的好地方。

您没有提供太多关于您的数据的信息,OSTSESSID 是否每次都相同长度,总是小写字母数字?

如果我们假设是这样,那么这是一个提示/你的答案的一半:

$pattern = "/OSTSESSID=([a-z0-9]{26});/";

希望这将对您有所帮助。

【讨论】:

    【解决方案2】:

    它不起作用的主要原因是你在 .* 上得到了一个贪婪的匹配

    它试图匹配尽可能多的字符。在星号后面加上一个问号会使它变得不贪心:

    OSTSESSID=(.?);过期=(.?;) (我还用分号终止了 expires 位 并且只匹配 sn-ps :

    OSTSESSID=mcnb8h1apihg9ffav1ubtgal77; expires=星期六,2015 年 5 月 9 日 11:49:58 GMT; 和 OSTSESSID=sugrlug6sj8m27lrkv5id9v473; expires=2015 年 5 月 9 日星期六 11:49:58 GMT;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      相关资源
      最近更新 更多