说我有以下内容:
$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 = "19.5";
所以它基本上抓住了这一部分的最新内容:time=19.5 ms ---
谢谢
修改
我想我已经弄明白了:
$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]);
我不知道这是否是正确的方法,但似乎有用吗?
答案 0 :(得分:4)
试试这个:
$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;
}
将回应:
19.5
在您的情况下, $match[1]
将包含整个匹配(time=19.5
),$match[1]
包含模式中的匹配组1:数字19.5
。< / p>
答案 1 :(得分:1)
preg_match("/time=([\d.]+).ms/",$var,$matches);
//var_dump($matches)
//$match[1] now holds the 19.5
?>
享受
答案 2 :(得分:1)
这可以通过preg_match
:
if (preg_match("/time=(.*?) ms/", $line, $m)) {
$time = (float) $m[1];
}
或explode
:
$fields = explode("=", $line);
$time = (float) $fields[4];
答案 3 :(得分:1)
您可以使用以下模式检索此内容:
preg_match('/time=([^ ]+) /',$matches);
echo $matches[1]; // 19.5
在time=
之后匹配至少一个不是空格(+
)的字符([^ ]
)。
答案 4 :(得分:0)
在preg_match
来电
time=([\d\.]+)
答案 5 :(得分:0)
<?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;
?>
编辑:或者您可以将正则表达式编辑为:
preg_match("/time\s*=\s*([0-9.]+)/", $var, $matches);
这样它匹配“time = xx.x”或“time = xx.x”。