str_replace preg_match 挂起后 PHP

str_replace after preg_match hangs PHP

我正在尝试从返回的 header:

中检索值
HTTP/1.1 302 Moved Temporarily Date: Mon, 08 Jun 2015 00:48:51 GMT Server: Apache X-Powered-By: PHP/5.6.8 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 X-Frame-Options: SAMEORIGIN Set-Cookie: frontend=b09kg96q756cv2a08l9d6vbq07; expires=Mon, 08-Jun-2015 01:48:52 GMT; Max-Age=3600; path=/; domain=***-shop.***.nl; HttpOnly Location: http://commercive-shop.declaredemo.nl/commshopengine/index.php/customer/account/ X-Powered-By: PleskLin Content-Length: 0 Connection: close Content-Type: text/html; charset=UTF-8

我用正则表达式做这个,然后用 str_replace 清理它。但是 PHP 在这段代码之后挂起,似乎陷入了无限循环:

preg_match('/frontend=(.+); expires=/i', $output, $matches);
$sid = str_replace("frontend=","", $matches[0]);

我可以回显值 $matches[0],returns 期望值

frontend=scrcc1lhh01gdss5m6ala8n791; expires=

但是我不能str_replace这个值。我想去掉 frontend= 和 ; expires= 来自字符串并保留 scrcc1lhh01gdss5m6ala8n791.

我正在使用 PHP 5.6

您可以将 preg_match() 调用替换为 preg_replace() 调用,并将整个字符串替换为 ID,例如

echo $sid = preg_replace('/.*frontend=(.+); expires=.*/i', "", $str);

输出:

b09kg96q756cv2a08l9d6vbq07

或者只是不要使用 $matches[0] 正如 @Dagon 已经在评论中指出的那样,只需使用:$matches[1].

这将 return 正确的值。

preg_match('/frontend=(.+); expires=/i', $output, $matches);
$search  = array('expires=', ';', 'frontend=');
$replace = $matches;

$sid = str_replace($search,"", $replace);
echo $sid[0]. '<br>'.'<br>';
echo $sid[1];