从长字符串返回多行

时间:2016-03-01 01:55:44

标签: 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: no-cache
Server: nginx/1.7.9
Content-Length: 294
Connection: keep-alive

在"位置:"之后,我想将该行的所有数据保存到数组中。可能有3或4行要从大块文本中保存。

我怎么能这样做?

谢谢!

2 个答案:

答案 0 :(得分:1)

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

以下是一种方式:

  1. 在发生Location:
  2. 的位置拆分文本
  3. 将结果按新行拆分为数组
  4. Example:

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

    这是另一种方式:

    1. 使用正则表达式,匹配Location:及其后的所有内容
    2. 如上所述 - 用新行分割结果
    3. Example:

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

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

答案 1 :(得分:0)

我发现另一种方式也有效我想我会添加以防万一:

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

来源:Iterate over each line in a string in PHP 那里还有很多有用的其他方法。

相关问题