php int 字节,PHP将KB MB GB TB等转换为字节

这是我到目前为止所提出的,我认为这是一个更优雅的解决方案:

/**

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

}