PHP转换KB MB GB TB等字节。

时间:2022-03-11 21:38:48


I'm asking how to convert KB MB GB TB & co. into bytes.
For example:

我要问的是如何将KB MB GB TB & co.转换成字节。例如:

byteconvert("10KB") // => 10240
byteconvert("10.5KB") // => 10752
byteconvert("1GB") // => 1073741824
byteconvert("1TB") // => 1099511627776

and so on...

等等……

EDIT: wow. I've asked this question over 4 years ago. Thise kind of things really show you how much you've improved over time!

编辑:哇。我在四年前问过这个问题。这样的事情真的会让你知道你的进步有多大!

8 个解决方案

#1


25  

Only because I couldn't find anything besides the other way around on Google....

只是因为我在谷歌附近找不到别的东西

function convertToBytes($from){
    $number=substr($from,0,-2);
    switch(strtoupper(substr($from,-2))){
        case "KB":
            return $number*1024;
        case "MB":
            return $number*pow(1024,2);
        case "GB":
            return $number*pow(1024,3);
        case "TB":
            return $number*pow(1024,4);
        case "PB":
            return $number*pow(1024,5);
        default:
            return $from;
    }
}

#2


8  

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]);
}

#3


3  

<?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";
?>

#4


2  

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);
}

#5


2  

I use a function to determine the memory limit set for PHP in some cron scripts that looks like:

我在一些cron脚本中使用一个函数来确定PHP的内存限制。

$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'))));
}

#6


0  

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:

我知道这是一个相对旧的话题,但这是一个函数,我有时不得不使用当我需要这种东西;你可以借口如果功能不工作,我写这个手在移动:

funtion 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

和紧凑

funtion 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 ;)

Brodde85;)

#7


0  

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.

它适应了由Al Jey(空格处理)和John V(切换用例)提供的一些想法,但是没有regex,不调用pow(),让切换用例在没有中断时做它的事情,并且可以处理一些奇怪的用户输入(例如:“125952”结果是125952。我确信有一个更优化的解决方案,它涉及的指令更少,但是代码不那么干净/易读。

#8


0  

One more solution (IEC):

一个解决方案(IEC):

<?php

class Filesize
{
    const UNIT_PREFIXES_POWERS = [
        'B' => 0,
        ''  => 0,
        'K' => 1,
        'k' => 1,
        'M' => 2,
        'G' => 3,
        'T' => 4,
        'P' => 5,
        'E' => 6,
        'Z' => 7,
        'Y' => 8,
    ];

    public static function humanize($size, int $precision = 2, bool $useBinaryPrefix = false)
    {
        $base = $useBinaryPrefix ? 1024 : 1000;
        $limit = array_values(self::UNIT_PREFIXES_POWERS)[count(self::UNIT_PREFIXES_POWERS) - 1];
        $power = ($_ = floor(log($size, $base))) > $limit ? $limit : $_;
        $prefix = array_flip(self::UNIT_PREFIXES_POWERS)[$power];
        $multiple = ($useBinaryPrefix ? strtoupper($prefix) . 'iB' : $prefix . 'B');
        return round($size / pow($base, $power), $precision) . $multiple;
    }

    // ...
}

Source:

来源:

https://github.com/mingalevme/utils/blob/master/src/Filesize.php https://github.com/mingalevme/utils/blob/master/tests/FilesizeTest.php

https://github.com/mingalevme/utils/blob/master/src/Filesize.php https://github.com/mingalevme/utils/blob/master/tests/FilesizeTest.php

#1


25  

Only because I couldn't find anything besides the other way around on Google....

只是因为我在谷歌附近找不到别的东西

function convertToBytes($from){
    $number=substr($from,0,-2);
    switch(strtoupper(substr($from,-2))){
        case "KB":
            return $number*1024;
        case "MB":
            return $number*pow(1024,2);
        case "GB":
            return $number*pow(1024,3);
        case "TB":
            return $number*pow(1024,4);
        case "PB":
            return $number*pow(1024,5);
        default:
            return $from;
    }
}

#2


8  

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]);
}

#3


3  

<?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";
?>

#4


2  

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);
}

#5


2  

I use a function to determine the memory limit set for PHP in some cron scripts that looks like:

我在一些cron脚本中使用一个函数来确定PHP的内存限制。

$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'))));
}

#6


0  

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:

我知道这是一个相对旧的话题,但这是一个函数,我有时不得不使用当我需要这种东西;你可以借口如果功能不工作,我写这个手在移动:

funtion 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

和紧凑

funtion 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 ;)

Brodde85;)

#7


0  

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.

它适应了由Al Jey(空格处理)和John V(切换用例)提供的一些想法,但是没有regex,不调用pow(),让切换用例在没有中断时做它的事情,并且可以处理一些奇怪的用户输入(例如:“125952”结果是125952。我确信有一个更优化的解决方案,它涉及的指令更少,但是代码不那么干净/易读。

#8


0  

One more solution (IEC):

一个解决方案(IEC):

<?php

class Filesize
{
    const UNIT_PREFIXES_POWERS = [
        'B' => 0,
        ''  => 0,
        'K' => 1,
        'k' => 1,
        'M' => 2,
        'G' => 3,
        'T' => 4,
        'P' => 5,
        'E' => 6,
        'Z' => 7,
        'Y' => 8,
    ];

    public static function humanize($size, int $precision = 2, bool $useBinaryPrefix = false)
    {
        $base = $useBinaryPrefix ? 1024 : 1000;
        $limit = array_values(self::UNIT_PREFIXES_POWERS)[count(self::UNIT_PREFIXES_POWERS) - 1];
        $power = ($_ = floor(log($size, $base))) > $limit ? $limit : $_;
        $prefix = array_flip(self::UNIT_PREFIXES_POWERS)[$power];
        $multiple = ($useBinaryPrefix ? strtoupper($prefix) . 'iB' : $prefix . 'B');
        return round($size / pow($base, $power), $precision) . $multiple;
    }

    // ...
}

Source:

来源:

https://github.com/mingalevme/utils/blob/master/src/Filesize.php https://github.com/mingalevme/utils/blob/master/tests/FilesizeTest.php

https://github.com/mingalevme/utils/blob/master/src/Filesize.php https://github.com/mingalevme/utils/blob/master/tests/FilesizeTest.php