PHP convert KB MB GB TB etc to Bytes

后端 未结 8 2470
长发绾君心
长发绾君心 2020-12-16 18:53


I\'m asking how to convert KB MB GB TB & co. into bytes.
For example:

byteconvert(\"10KB\") // => 10240
byteconvert(\"10.5KB\") // =>          


        
8条回答
  •  感情败类
    2020-12-16 19:41

    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));
    

    Output:

    array(5) { [0]=> int(13) [1]=> int(13) [2]=> int(13312) [3]=> int(10752) [4]=> NULL } int(1)

提交回复
热议问题