Mathieu De Keyzer's face

 PHP - Convert Human Readable Size to Bytes

HTTP enthusiasts

Solution

We are talking of that kind of strings:

  • 24m
  • 24MB
  • 4G
  • 12Kb

To be converted like these:

  • 24*1024*1024 = 25.165.824
  • 24*1024*1024 = 25.165.824
  • 4*1024*1024*1024 = 4.294.967.296
  • 12*1024 = 12.288

And my solution is

    function humanReadableSizeToBytes(Options $options, string $value): int 
    {
        $matches = [];
        \preg_match('/^\s*(?P<number>\d+)\s*(?:(?P<prefix>[kmgt]?)b?)?\s*$/i', $value, $matches);

        $bytes = \intval($matches['number'] ?? 0);
        $prefix = \strtolower(\strval($matches['prefix'] ?? ''));
        switch ($prefix) {
            case 't': $bytes *= 1024;
            // no break
            case 'g': $bytes *= 1024;
            // no break
            case 'm': $bytes *= 1024;
            // no break
            case 'k': $bytes *= 1024;
        }

        return $bytes;
    };

the trick is to not have break sentences in the switch. So If a have 'g' size the $bytes size will be mutiplicated by the g's 1024 then the m's 1024 and finally the k's 1024.