PHP将KB MB GB GB TB等转换为字节 [英] PHP convert KB MB GB TB etc to Bytes
本文介绍了PHP将KB MB GB GB TB等转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我问如何转换KB MB GB TB&公司成字节.
例如:
I'm asking how to convert KB MB GB TB & co. into bytes.
For example:
byteconvert("10KB") // => 10240
byteconvert("10.5KB") // => 10752
byteconvert("1GB") // => 1073741824
byteconvert("1TB") // => 1099511627776
以此类推...
哇.我在4年前问过这个问题.这类事情真的可以告诉您,随着时间的推移,您已经进步了多少!
wow. I've asked this question over 4 years ago. Thise kind of things really show you how much you've improved over time!
推荐答案
以下是实现此目的的功能:
Here's a function to achieve this:
function convertToBytes(string $from): ?int {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$number = substr($from, 0, -2);
$suffix = strtoupper(substr($from,-2));
//B or no suffix
if(is_numeric(substr($suffix, 0, 1))) {
return preg_replace('/[^\d]/', '', $from);
}
$exponent = array_flip($units)[$suffix] ?? null;
if($exponent === null) {
return null;
}
return $number * (1024 ** $exponent);
}
$testCases = ["13", "13B", "13KB", "10.5KB", "123Mi"];
var_dump(array_map('convertToBytes', $testCases));
输出:
array(5){[0] => int(13)[1] => int(13)[2] => int(13312)[3] => int(10752)[4] => NULL} int(1)
array(5) { [0]=> int(13) [1]=> int(13) [2]=> int(13312) [3]=> int(10752) [4]=> NULL } int(1)
这篇关于PHP将KB MB GB GB TB等转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文