Php 从长字符串返回多行

Php 从长字符串返回多行,php,Php,我有一个包含多个头信息实例的大字符串。例如: 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

我有一个包含多个头信息实例的大字符串。例如:

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
在“Location:”之后,我想将该行中的所有数据保存到一个数组中。一大块文本中可能有3或4行需要保存

我怎么能这样做


谢谢

有很多方法可以做到这一点

这里有一个方法:
  • 位置:
    出现的位置将文本拆分
  • 按新行将结果拆分为数组
  • 还有一种方法:
  • 使用正则表达式,匹配
    位置:
    及其后面的所有内容
  • 如上所述-将结果拆分为新行

  • 注意:
    s
    修饰符表示将新行作为
    的一部分进行匹配-否则它们将被忽略,新行将终止捕获。

    我找到了另一种方法,我想我会添加它,以防对任何人都有帮助:

    foreach(preg_split("/((\r?\n)|(\r\n?))/", $bigString) as $line){
        if (strpos($line, 'Location') !== false) {
            // Do stuff with the line
        }
    } 
    
    资料来源:
    还有很多其他有用的方法。

    这只会给出包含
    位置的行。
    preg_match_all('~(Location:.+)~s', $text, $output);
    $output = explode(PHP_EOL, $output[0][0]);
    
    foreach(preg_split("/((\r?\n)|(\r\n?))/", $bigString) as $line){
        if (strpos($line, 'Location') !== false) {
            // Do stuff with the line
        }
    }