PHP convert KB MB GB TB etc to Bytes

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

    Here's what I've come up with so far, that I think is a much more elegant solution:

    /**
     * Converts a human readable file size value to a number of bytes that it
     * represents. Supports the following modifiers: K, M, G and T.
     * Invalid input is returned unchanged.
     *
     * Example:
     * <code>
     * $config->human2byte(10);          // 10
     * $config->human2byte('10b');       // 10
     * $config->human2byte('10k');       // 10240
     * $config->human2byte('10K');       // 10240
     * $config->human2byte('10kb');      // 10240
     * $config->human2byte('10Kb');      // 10240
     * // and even
     * $config->human2byte('   10 KB '); // 10240
     * </code>
     *
     * @param number|string $value
     * @return number
     */
    public function human2byte($value) {
      return preg_replace_callback('/^\s*(\d+)\s*(?:([kmgt]?)b?)?\s*$/i', function ($m) {
        switch (strtolower($m[2])) {
          case 't': $m[1] *= 1024;
          case 'g': $m[1] *= 1024;
          case 'm': $m[1] *= 1024;
          case 'k': $m[1] *= 1024;
        }
        return $m[1];
      }, $value);
    }
    
    0 讨论(0)
  • 2020-12-16 19:31
    <?php
    function byteconvert($input)
    {
        preg_match('/(\d+)(\w+)/', $input, $matches);
        $type = strtolower($matches[2]);
        switch ($type) {
        case "b":
            $output = $matches[1];
            break;
        case "kb":
            $output = $matches[1]*1024;
            break;
        case "mb":
            $output = $matches[1]*1024*1024;
            break;
        case "gb":
            $output = $matches[1]*1024*1024*1024;
            break;
        case "tb":
            $output = $matches[1]*1024*1024*1024;
            break;
        }
        return $output;
    }
    $foo = "10mb";
    echo "$foo = ".byteconvert($foo)." byte";
    ?>
    
    0 讨论(0)
  • 2020-12-16 19:31

    Wanting something similar to this and not quite liking the other solutions posted here for various reasons, I decided to write my own function:

    function ConvertUserStrToBytes($str)
    {
        $str = trim($str);
        $num = (double)$str;
        if (strtoupper(substr($str, -1)) == "B")  $str = substr($str, 0, -1);
        switch (strtoupper(substr($str, -1)))
        {
            case "P":  $num *= 1024;
            case "T":  $num *= 1024;
            case "G":  $num *= 1024;
            case "M":  $num *= 1024;
            case "K":  $num *= 1024;
        }
    
        return $num;
    }
    

    It adapts a few of the ideas presented here by Al Jey (whitespace handling) and John V (switch-case) but without the regex, doesn't call pow(), lets switch-case do its thing when there aren't breaks, and can handle some weird user inputs (e.g. " 123 wonderful KB " results in 125952). I'm sure there is a more optimal solution that involves fewer instructions but the code would be less clean/readable.

    0 讨论(0)
  • 2020-12-16 19:38

    I know this is a relative old topic, but here's a function that I sometimes have to use when I need this kind of stuff; You may excuse for if the functions dont work, I wrote this for hand in a mobile:

    function intobytes($bytes, $stamp = 'b') {
        $indx = array_search($stamp, array('b', 'kb', 'mb', 'gb', 'tb', 'pb', 'yb'));
        if ($indx > 0) {
            return $bytes * pow(1024, $indx);
        }
        return $bytes;
    }
    

    and as compact

    function intobytes($bytes, $stamp='b') {$indx=array_search($stamp,array('b','kb','mb','gb','tb','pb','yb'));if($indx > 0){return $bytes * pow(1024,$indx);} return $bytes;}
    

    Take care!

    Brodde85 ;)

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 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'))));
    }
    
    0 讨论(0)
提交回复
热议问题