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

前端 未结 6 572
抹茶落季
抹茶落季 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:58

    I can only think of a slight variation on what you're doing:

    function int_from_bytestring($byteString) {
      $ret = 0;
      if (preg_match('!^\s*(\d+(?:\.\d+))\s*([KMNGTPE])B?\s*$!', $byteString, $matches)) {
        $suffix = " KMGTPE";
        $index = strpos($suffix, $matches[2]);
        if ($index !== false) {
          $ret = $matches[1];
          while ($index--) {
            $matches *= 1024;
          }
        }
      }
      return intval($ret);
    }
    

提交回复
热议问题