str_replace after preg_match hangs PHP

383 views Asked by At

I am trying to retrieve a value from a returned 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

i do this with a regular expression and clean it up with str_replace. However PHP hangs after this code and seems to go in some endless loop:

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

I can echo the value $matches[0] which returns the expected value

frontend=scrcc1lhh01gdss5m6ala8n791; expires=

but I can not str_replace the value. I want to strip frontend= and ; expires= from the string and keep scrcc1lhh01gdss5m6ala8n791.

I am using PHP 5.6

2

There are 2 answers

2
Rizier123 On BEST ANSWER

You can replace your preg_match() call with a preg_replace() call and replace the entire string with the id, e.g.

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

output:

b09kg96q756cv2a08l9d6vbq07

Or just don't use $matches[0] as @Dagon already pointed out in the comments and just use: $matches[1].

4
Jason Byrd On

This will return the correct value.

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