I need to test the value returned by ini_get('memory_limit')
and increase the memory limit if it is below a certain threshold, however this ini_get('memory_limit')
call returns string values like '128M' rather than integers.
I know I can write a function to parse these strings (taking case and trailing 'B's into account) as I have written them numerous times:
function int_from_bytestring ($byteString) {
preg_match('/^\s*([0-9.]+)\s*([KMGTPE])B?\s*$/i', $byteString, $matches);
$num = (float)$matches[1];
switch (strtoupper($matches[2])) {
case 'E':
$num = $num * 1024;
case 'P':
$num = $num * 1024;
case 'T':
$num = $num * 1024;
case 'G':
$num = $num * 1024;
case 'M':
$num = $num * 1024;
case 'K':
$num = $num * 1024;
}
return intval($num);
}
However, this gets tedious and this seems like one of those random things that would already exist in PHP, though I've never found it. Does anyone know of some built-in way to parse these byte-amount strings?