2011-09-12 2 views
1

PHP에서 ping 요청의 응답 시간을 grep하려고합니다. 내가 값을 2.33 MS를 추출하기 위해 찾고 있지만, time= 실 거예요 작업을 검색하여 문자열을하고있는 중이 야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 

응답 시간이 XX.XX 또는 xxx.xx. 될 수 있기 때문에, : 같은 응답이 보인다 길이는 가변적이다.

가장 좋은 방법은? 그들이 만드는 -

+0

나는 그것을 깨닫지 못하고 머리에 쥐어 놨다 고 생각한다. grep. Regexes는 당신의 친구입니다. –

답변

4

이 정규식은 소수점 이하 두 자리

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

그리고

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

?> 
+0

대단히 감사합니다. – Justin

+1

소수점을 포함하지 않는 173 ms와 일치하는 정규 표현식에 문제가있었습니다. 그래서'preg_match ('/ time \ = ([0-9 \.] +) ms /', $ str, $ matches); 대신'preg_match '를 사용하고 있습니다. –

1

당신은 정규 표현식을 배울 필요가 몇 가지 예제 PHP 코드에

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

작업 및 절단한다 이와 같은 것은 거의 없습니다.

,

http://us.php.net/preg_match

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

비록 당신이 머리카락을 분할 할 경우, 그들은 여기에 정말 필요한 아니에요. 2 번 라인 출력이 항상 원하는 경우, 그 라인을 가져 가면 http://us2.php.net/strrpos을 사용하여 라인에서 마지막 등호 기호의 위치를 ​​찾은 다음 그 라인의 끝에서부터 끝까지 모든 것을 잡아서 마지막 라인을 해킹합니다. 세 문자 "ms". 시간 낭비 야.