【问题标题】:Logic of PHP & Get Section of an ArrayPHP的逻辑和数组的获取部分
【发布时间】:2017-04-18 11:34:13
【问题描述】:

我找到了一段代码,它通过 php 显示对服务器的 ping,我想知道是否可以实现不同的输出,但我正在努力确定逻辑。

代码:

             <?php
             $cmd = "ping 8.8.8.8 -c 1";

             $descriptorspec = array(
             0 => array("pipe", "r"),   // stdin is a pipe that the child will read from
             1 => array("pipe", "w"),   // stdout is a pipe that the child will write to
             2 => array("pipe", "w")    // stderr is a pipe that the child will write to
             );
             flush();
             $process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());
             echo "<pre>";
             if (is_resource($process)) {
                 while ($s = fgets($pipes[1])) {
                     print $s;
                 }
             }
             echo "</pre>";
             ?>

电流输出:

PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=54 time=28.278 ms

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 packets received, 0% packet loss
round-trip min/avg/max = 28.278/28.278/28.278 ms

想要的输出:

我只想要毫秒值或“时间”

28.278

试验:

我尝试通过以下代码运行它来获取“$s”或“$pipes”变量/数组的值,包括一些数组值“[1]”等的试验:

str_replace("time=","@@",$test_stringget_ping_res);
str_replace(" ms","@@",$test_stringget_ping_res);

但我收到“无法打开规则文件”。

【问题讨论】:

  • 所以你只需要时间 ?
  • @Rahul 是的,从第二行开始!

标签: php arrays regex logic output


【解决方案1】:

您可以使用preg_match(),如下所示。

preg_match('/time=(.*?) ms/', $s, $m );
print $m[1];

您的代码如下:

 if (is_resource($process)) {
 while ($s = fgets($pipes[1])) {
     preg_match('/time=(.*?) ms/', $s, $m );
     print $m[1];
     print $s;
   }
 }

解释:简单地捕获time=ms 之间的所有内容。

Ideone Demo

查看preg_match() 文档以供使用。

【讨论】:

    【解决方案2】:

    您可以将命令更改为:

    ping -c 1 8.8.8.8 | tail -1 | cut -d/ -f 5
    

    【讨论】:

    • 谢谢,不过我还需要其他地方的全部输出!
    猜你喜欢
    • 2022-01-22
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    相关资源
    最近更新 更多