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 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试