ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、视频、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## **将字节转为可读的KB G M** ``` function FileSizeConvert($bytes) { $bytes = floatval($bytes); $arBytes = array( 0 => array( "UNIT" => "TB", "VALUE" => pow(1024, 4) ), 1 => array( "UNIT" => "GB", "VALUE" => pow(1024, 3) ), 2 => array( "UNIT" => "MB", "VALUE" => pow(1024, 2) ), 3 => array( "UNIT" => "KB", "VALUE" => 1024 ), 4 => array( "UNIT" => "B", "VALUE" => 1 ), ); foreach($arBytes as $arItem) { if($bytes >= $arItem["VALUE"]) { $result = $bytes / $arItem["VALUE"]; $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"]; break; } } return $result; } ``` 方法2: ``` function display_filesize($filesize){ if(is_numeric($filesize)){ $decr = 1024; $step = 0; $prefix = array('Byte','KB','MB','GB','TB','PB'); while(($filesize / $decr) > 0.9){ $filesize = $filesize / $decr; $step++; } return round($filesize,2).' '.$prefix[$step]; } else { return 'NaN'; } } //1024*1024=1048576 echo display_filesize("1048576");//1M echo display_filesize("1045111");//1M echo display_filesize("1048876");//1M ``` ## **转字节** ``` function StringSizeToBytes($Size){ $Unit = strtolower($Size); $Unit = strtolower(preg_replace('/[^a-z]/', '', $Unit)); $Value = intval(preg_replace('/[^0-9]/', '', $Size)); $Units = array('b'=>0, 'kb'=>1,'k'=>1, 'mb'=>2,'m'=>2, 'gb'=>3,'g'=>3, 'tb'=>4,'t'=>4); $Exponent = isset($Units[$Unit]) ? $Units[$Unit] : 0; return ($Value * pow(1024, $Exponent)); } echo StringSizeToBytes("1Mb");//1048576 ``` 方法2: ``` function return_bytes($val) { //取出空格 $val = trim($val); //获取字符串最后一个索引并且strtolower转小写 $Unit= strtolower(preg_replace("/^[0-9]/", '', $val)); switch($Unit) { case 't': case 'tb': $val *= 1024; case 'g': case 'gb': $val *= 1024; case 'm': case 'mb': $val *= 1024; case 'k': case 'kb': $val *= 1024; } return $val; } echo return_bytes("1M"); ```