我需要测试返回的值,ini_get('memory_limit')如果它低于某个阈值,则增加内存限制,但是这个ini_get('memory_limit')调用返回字符串值,如'128M'而不是整数.
我知道我可以编写一个函数来解析这些字符串(将案例和尾随'B'考虑在内),因为我已多次编写它们:
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);
}
Run Code Online (Sandbox Code Playgroud)
然而,这变得乏味,这似乎是PHP中已经存在的随机事物之一,尽管我从来没有找到它.有谁知道解析这些字节数量字符串的一些内置方法?
我觉得你运气不好.ini_get()的PHP手册实际上在关于ini_get()如何返回ini值的警告中解决了这个特定问题.
他们在其中一个例子中提供了一个函数来完成这个,所以我猜它是要走的路:
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
Run Code Online (Sandbox Code Playgroud)
他们对上述函数有这样的说法:"上面的例子显示了一种将速记符号转换为字节的方法,就像PHP源代码一样."
或一些较短的版本,如果您愿意
function toInteger ($string)
{
sscanf ($string, '%u%c', $number, $suffix);
if (isset ($suffix))
{
$number = $number * pow (1024, strpos (' KMG', strtoupper($suffix)));
}
return $number;
}
Run Code Online (Sandbox Code Playgroud)