开发者

PHP Searching Ping Result For Response Time

I am trying to grep the response time from a ping request in php. The response looks like:

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

I am looking开发者_高级运维 to extract the value 2.33 ms, but doing a substring by searching for time= wont work, because the response time could be xx.xx or xxx.xx. Its length is variable.

Best way to do this?


This regex should work

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

And cutting it to two decimal places

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

And some sample PHP code

<?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];

?>


You need to learn regular expressions - they make something like this almost trivial:

http://us.php.net/preg_match

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

Though if you want to split hairs, they're not truly necessary here. If line #2 of your output is always what you want, then you take that line, use http://us2.php.net/strrpos to find the position of the last equals sign in the line, grab everything from there to the end of the line, and hack off the last three characters " ms". That should leave you with the time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜