【问题标题】:php preg match get only last matched stringphp preg match 仅获取最后匹配的字符串
【发布时间】:2016-04-30 09:51:23
【问题描述】:

我需要获取最后的 HTTP 标头。我的字符串是:

HTTP/1.1 302 Moved Temporarily
Date: Sat, 30 Apr 2016 09:48:56 GMT
Server: Apache
X-Powered-By: PHP/5.5.34
Location: 2.php
Content-Length: 0
Content-Type: text/html

HTTP/1.1 302 Moved Temporarily
Date: Sat, 30 Apr 2016 09:48:57 GMT
Server: Apache
X-Powered-By: PHP/5.5.34
Location: 3.php
Content-Length: 0
Content-Type: text/html

HTTP/1.1 200 OK
Date: Sat, 30 Apr 2016 09:48:57 GMT
Server: Apache
X-Powered-By: PHP/5.5.34
Transfer-Encoding: chunked
Content-Type: text/html

但我需要获取最后一个标题。我试图用 \n\n 分解这个字符串,但我无法得到结果。是否可以使用 preg_match 做到这一点?

【问题讨论】:

    标签: php curl preg-match explode


    【解决方案1】:

    明白了! 我需要用这段代码来爆炸它:

    explode("\r\n\r\n", $header);
    

    【讨论】:

      【解决方案2】:

      使用preg_splitarray_pop函数的解决方案:

      // $headers is your initial string
      $headers_splitted = preg_split("/\R{2}/", $headers);
      
      print_r(array_pop($headers_splitted));
      

      输出:

      HTTP/1.1 200 OK
      Date: Sat, 30 Apr 2016 09:48:57 GMT
      Server: Apache
      X-Powered-By: PHP/5.5.34
      Transfer-Encoding: chunked
      Content-Type: text/html
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多