PHP搜索响应时间的Ping结果

时间:2011-09-12 02:26:51

标签: php regex string

我正在尝试从php中的ping请求中获取响应时间。回复如下:

PING server.domain.com (XXX.XXX.XXX.XXX) 56(84) bytes of data.
64 bytes from XXX.XXX.XXX.XXX: icmp_seq=1 ttl=58 time=2.33 ms

--- server.domain.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 2.332/2.332/2.332/0.000 ms

我希望提取值2.33 ms,但是通过搜索time=来执行子字符串不会起作用,因为响应时间可能是xx.xx或xxx.xx.它的长度是可变的。

最好的方法吗?

2 个答案:

答案 0 :(得分:4)

这个正则表达式应该可行

/time\=([0-9]+\.[0-9]+) ms/

并将其缩小到小数点后两位

/time\=([0-9]+\.[0-9]{2}) ms/

一些示例PHP代码

<?php

$str = '64 bytes from XXX.XXX.XXX.XXX: icmp_seq=1 ttl=58 time=2.33 ms';

    // $result will contain the number of matches - in this case, 1
$result = preg_match('/time\=([0-9]+\.[0-9]{2}) ms/', $str, $matches);
    // You can call it like this as well, if you don't care about the number of matches
preg_match('/time\=([0-9]+\.[0-9]{2}) ms/', $str, $matches);

print_r($matches);
echo $matches[1];

?>

答案 1 :(得分:1)

你需要学习正则表达式 - 他们这样做的东西几乎是微不足道的:

http://us.php.net/preg_match

http://us.php.net/manual/en/pcre.pattern.php

虽然如果你想分裂头发,但这里并不是真的有必要。如果输出的第2行总是你想要的,那么你拿走那一行,用http://us2.php.net/strrpos找到行中最后一个等号的位置,抓住从那里到行尾的所有内容,砍掉最后三个字符“ms”。这应该让你有时间。