【问题标题】:Return multiple lines from a long string从长字符串返回多行
【发布时间】:2016-06-13 07:19:10
【问题描述】:

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

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 行。

我该怎么做?

谢谢!

【问题讨论】:

    标签: php


    【解决方案1】:

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

    这是一种方法:

    1. 在出现Location: 的位置拆分文本
    2. 将结果按新行拆分为数组

    Example:

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

    这是另一种方式:

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

    Example:

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

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

    【讨论】:

      【解决方案2】:

      我发现了另一种可行的方法,我想我会添加以防它对任何人有帮助:

      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 里面还有很多其他有用的方法。

      【讨论】:

      • 那只会给你包含Location的行
      猜你喜欢
      • 1970-01-01
      • 2018-07-24
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2017-05-12
      相关资源
      最近更新 更多