preg match - str_replace after preg_match hangs PHP


preg match - str_replace after preg_match hangs PHP

我正在尝试从返回的头部检索值:

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],它返回期望的值

frontend=scrcc1lhh01gdss5m6ala8n791; expires=

,但我不能str_replace值。我想去掉frontend= and;过期=从字符串中保存sccc1lhh01gdss5m6ala8n791 .

我使用PHP 5.6

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

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

b09kg96q756cv2a08l9d6vbq07

或者就像@Dagon已经在评论中指出的那样,不要用$matches[0],直接用:$matches[1]

这将返回正确的值。

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