PHP convert KB MB GB TB etc to Bytes

后端 未结 8 2469
长发绾君心
长发绾君心 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

    I use a function to determine the memory limit set for PHP in some cron scripts that looks like:

    $memoryInBytes = function ($value) {
        $unit = strtolower(substr($value, -1, 1));
        return (int) $value * pow(1024, array_search($unit, array(1 =>'k','m','g')));
    }
    

    A similar approach that will work better with floats and accept the two letter abbreviation would be something like:

    function byteconvert($value) {
        preg_match('/(.+)(.{2})$/', $value, $matches);
        list($_,$value,$unit) = $matches;
        return (int) ($value * pow(1024, array_search(strtolower($unit), array(1 => 'kb','mb','gb','tb'))));
    }
    

提交回复
热议问题