PHP convert KB MB GB TB etc to Bytes

后端 未结 8 2476
长发绾君心
长发绾君心 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:
     * 
     * $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
     * 
     *
     * @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);
    }
    

提交回复
热议问题