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.
Last posts
- Draw.io on a website
- Deploy elasticms on AWS
- Intégrer BOSA Accessibility Check dans un site web [Content in French]
- PHP - Convert Human Readable Size to Bytes
- Composer: How to use a specific branch acting like a specific revision in composer dependencies
- Stream a CSV from a JSON array
- Comment utiliser les commandes "locales" du skeleton [Content in French]
- How to extract data from a JsonMenuNestedEditorField
- Backup on AWS glacier
- Refer to environment variables in twig