PHP convert KB MB GB TB etc to Bytes

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

    function toByteSize($p_sFormatted) {
        $aUnits = array('B'=>0, 'KB'=>1, 'MB'=>2, 'GB'=>3, 'TB'=>4, 'PB'=>5, 'EB'=>6, 'ZB'=>7, 'YB'=>8);
        $sUnit = strtoupper(trim(substr($p_sFormatted, -2)));
        if (intval($sUnit) !== 0) {
            $sUnit = 'B';
        }
        if (!in_array($sUnit, array_keys($aUnits))) {
            return false;
        }
        $iUnits = trim(substr($p_sFormatted, 0, strlen($p_sFormatted) - 2));
        if (!intval($iUnits) == $iUnits) {
            return false;
        }
        return $iUnits * pow(1024, $aUnits[$sUnit]);
    }
    

提交回复
热议问题