PHP convert KB MB GB TB etc to Bytes PHP convert KB MB GB TB etc to Bytes php php

PHP convert KB MB GB TB etc to Bytes


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)


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


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