如何使用PHP中的正则表达式从这种字符串中获取百分比和文件大小?
问题是我使用print_r函数得到这个字符串,如下所示:
while(!feof($handle))
{
$progress = fread($handle, 8192);
print_r($progress);
}
以上输出如下:
[download] 28.8% of 1.51M at 171.30k/s ETA 00:06
我确定我需要使用像preg_match这样的东西,但不知道如何为数组做这个以及如何引用字符串。正则表达式需要放在循环中。
感谢您的帮助。
答案 0 :(得分:3)
试试这个:
foreach ($progress as $str) {
if (preg_match_all('/\[download] (\d+\.\d)% of (\d+\.\d+\w)/', $str, $matches)) {
var_dump($matches);
}
}
答案 1 :(得分:1)
$string = '[download] 28.8% of 1.51M at 171.30k/s ETA 00:06
[download] 41.8% of 1.51M at 178.19k/s ETA 00:05';
// $string = file_get_contents($file_path);
$pattern = '/(?<percent>[0-9]{1,2}\.[0-9]{1,2})% of (?<filesize>.+) at/';
preg_match_all($pattern, $string, $matches);
print_r($matches);
答案 2 :(得分:0)
您也可以使用:
$parts = explode(' ', trim($progress));
$progressPercentage = floatval($parts[1]);
它可能比正则表达式更快,更容易阅读。
答案 3 :(得分:0)
因为您的字符串是可预测的格式并且重点是提取而不是验证,我同意@gitaarik 的观点,因为 explode()
可能是合适的。
在空格上拆分字符串,在您拥有所有所需元素后,再向爆炸限制添加一个元素,以便所有“剩余物”都倾泻到最后一个元素中。
使用 array destructuring syntax,您可以仅声明您打算使用的变量。
好处将是代码性能、可读性,并且不需要正则表达式知识。
代码:(Demo)
$string = '[download] 28.8% of 1.51M at 171.30k/s ETA 00:06';
// splits: 0--------| 1---| 2| 3---| 4--------------------|
[, $percent, , $size, ] = explode(' ', $string, 5);
var_export(['percent' => $percent, 'size' => $size]);
输出:
array (
'percent' => '28.8%',
'size' => '1.51M',
)