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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?