douwei1921 2015-05-08 14:34
浏览 105
已采纳

从数组循环返回值并匹配关键字(php)

I have an array $headers that looks like this and I want to extract the server name only. The problem is the data is not always in the same order so I need to search for "Server" and return its value. I imagine i need to use a loop but cant figure out how to incorporate the search.

Sample of array $headers

array(13) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(19) "Server: nginx/1.6.2"
  [2]=>
  string(35) "Date: Fri, 08 May 2015 14:27:28 GMT"
  [3]=>
  string(38) "Content-Type: text/html; charset=utf-8"
  [4]=>
  string(17) "Connection: close"
  [5]=>
  string(25) "X-Powered-By: PHP/5.6.7-1"
  [6]=>
  string(44) "Last-Modified: Fri, 08 May 2015 14:20:12 GMT"
}

I would like to extract the server name nginx/1.6.2

Here is my loop that I need to build upon

foreach ($headers as $value) {
    echo "$value
";
}
  • 写回答

2条回答 默认 最新

  • dtvx3420 2015-05-08 14:52
    关注
    $a = [
        "HTTP/1.1 200 OK",
        "Server: nginx/1.6.2",
        "Date: Fri, 08 May 2015 14:27:28 GMT",
        "Content-Type: text/html; charset=utf-8",
        "Connection: close",
        "X-Powered-By: PHP/5.6.7-1",
        "Last-Modified: Fri, 08 May 2015 14:20:12 GMT"
        ];
    
    preg_match('/^Server: (.*)$/m', implode(PHP_EOL, $a), $matches);
    echo $matches[1], PHP_EOL;
    

    Output:

    nginx/1.6.2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上