preg_match question, how to do this?
Say I have the following:
$var = "127.0.0.1 (127.0.0.1) 56(84) b开发者_高级运维ytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms ";
How can I return so it just says
$var2 = "19.5";
So it basically grabs whats in this part: time=19.5 ms ---
Thank you
EDIT
I think I have figured it out myself:
$var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms";
$var2 = preg_match("/time=(.*) ms ---/", $var, $matches);
print_r($matches[1]);
I don't know if this is the right way to do it, but it seems to work?
Try this:
$var = "127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms ";
if(preg_match('/time=(\d+\.\d+)/', $var, $match)) {
$var2 = $match[1];
echo $var2;
}
which will echo:
19.5
$match[1]
will contain the entire match (time=19.5
), in your case, and $match[1]
contains match group 1 from the pattern: which is the number 19.5
.
This could do it with preg_match
:
if (preg_match("/time=(.*?) ms/", $line, $m)) {
$time = (float) $m[1];
}
Or with explode
:
$fields = explode("=", $line);
$time = (float) $fields[4];
You could retrieve this with the following pattern:
preg_match('/time=([^ ]+) /',$matches);
echo $matches[1]; // 19.5
Matches after time=
at least one character (+
) that isn't a space ([^ ]
).
preg_match("/time=([\d.]+).ms/",$var,$matches);
//var_dump($matches)
//$match[1] now holds the 19.5
?>
Enjoy
Use this regex in your preg_match
call
time=([\d\.]+)
<?php
$var="127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=1 ttl=57 time=19.5 ms --- 127.0.0.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 19.548/19.548/19.548/0.000 ms ";
preg_match("/time=([0-9.]+)/", $var, $matches);
$var2 = $matches[1];
echo $var2;
?>
Edit: Or you can edit the regex to:
preg_match("/time\s*=\s*([0-9.]+)/", $var, $matches);
So that it matches "time=xx.x" or "time = xx.x".
精彩评论