PHP 将 KB MB GB TB 等转换为字节

2022-01-13 00:00:00 byte type-conversion php


我在问如何转换 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)

相关文章