LoginSignup
7
5

More than 5 years have passed since last update.

PHPでバイト数の単位アリナシを相互変換する

Last updated at Posted at 2014-09-04

intで渡してあげると、単位を付けて返してくれる。

ちなみにTB以上は対応してないから、自分で拡張しろ!

function prettyByte2Str($bytes)
{
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }
    return $bytes;
}

KB,MBなど単位がついた状態で渡すとByteにしてくれる

こっちもTB以上は対応してないから!

function prettyByte2Int($str)
{
    $result = str_ireplace(',', '', $str);
    $result = str_ireplace('.', '', $result);
    $result = str_ireplace(' ', '', $result);
    $result = str_ireplace('bytes', '', $result);
    $result = str_ireplace('byte', '', $result);
    $result = str_ireplace('b', '', $result);

    if (stripos($result, 'k')) {
        $result = (int)$result * 1024;
    } elseif (stripos($result, 'm')) {
        $result = (int)$result * 1048576;
    } elseif (stripos($result, 'g')) {
        $result = (int)$result * 1073741824;
    } else {
        $result = (int)$result;
    }
    return $result;
}
7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5