提取 header 中的 cookies 数据

Extract cookies data in header

我有这个随机字符串。我只需要字符串中的特定文本,例如 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);

但没有用。请帮我解决这个问题。

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

并使用 https://regex101.com/ 作为解决问题的好地方。

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

如果我们假设是这样,那么这里是 hint/half 你的答案:

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

希望这对您剩下的事情有所帮助。

它不起作用的主要原因是您在 .* 上进行贪婪匹配

它正在尝试匹配尽可能多的字符。 star后面丢个问号就很不贪心了:

OSTSESSID=(.?);到期=(.?;) (我还用分号终止了过期位 并且只匹配片段:

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