Is there an easy way in PHP to convert from strings like '256M', '180K', '4G' to their integer equivalents?

前端 未结 6 577
抹茶落季
抹茶落季 2021-01-08 01:22

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(\'me

6条回答
  •  日久生厌
    2021-01-08 01:45

    Since you will get an error with newer versions of PHP if the value has a CHAR at the end of it, you might need some extra testing:

    private function toBytes($str){
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        if (!is_numeric($last)) {
            $val = substr($val,0,strlen($val)-1);
            switch($last) {
                case 'g': $val *= 1024;
                case 'm': $val *= 1024;
                case 'k': $val *= 1024;
            }
        }
        return $val;
    }
    

    This works with no warnings

提交回复
热议问题