-1

I have a large string with multiple instances of header information. For example:

HTTP/1.1 302 Found
Cache-Control: no-cache, no-store, must-revalidate
Content-Type: text/html; charset=iso-8859-1
Date: Tue, 01 Mar 2016 01:43:13 GMT
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Location: http://www.google.com
Pragma: no-cache
Server: nginx/1.7.9
Content-Length: 294
Connection: keep-alive

After "Location:", I want to save all the data from that line to an array. There might be 3 or 4 lines to save from a big block of text.

How could I do this?

Thanks!

Wes
  • 866
  • 10
  • 19

2 Answers2

1

There are plenty of ways you could do this.

Here's one way:

  1. Split the text up at the point where Location: occurs
  2. Split the result by new lines into an array

Example:

$text = substr($text, strpos($text, 'Location:'));
$array = explode(PHP_EOL, $text);

Here's another way:

  1. Using regex, match Location: and everything after it
  2. As above - split the result by new lines

Example:

preg_match_all('~(Location:.+)~s', $text, $output);
$output = explode(PHP_EOL, $output[0][0]);

Note: the s modifier means match newlines as part of the . - they will otherwise be ignored and new lines will terminate the capture.

scrowler
  • 24,273
  • 9
  • 60
  • 92
0

I found another way that works too I figured I would add in case it helps anyone:

foreach(preg_split("/((\r?\n)|(\r\n?))/", $bigString) as $line){
    if (strpos($line, 'Location') !== false) {
        // Do stuff with the line
    }
} 

Source: Iterate over each line in a string in PHP There's a lot of helpful other ways in there too.

Community
  • 1
  • 1
Wes
  • 866
  • 10
  • 19