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

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)