Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 701
Adam Franco Avatar asked Aug 26 '09 18:08

Adam Franco


People also ask

How do I convert a string to a number in PHP?

Method 1: Using number_format() Function. The number_format() function is used to convert string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure. echo number_format( $num , 2);

What are the functions that you can use to convert strings to number types in PHP?

In PHP you can use intval(string) or floatval(string) functions to convert strings to numbers.

How do you convert one variable type to another in PHP?

PHP settype() Function The settype() function converts a variable to a specific type.

Can we add string and int in PHP?

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.


1 Answers

Or some shorter version, if you please

function toInteger ($string)
{
    sscanf ($string, '%u%c', $number, $suffix);
    if (isset ($suffix))
    {
        $number = $number * pow (1024, strpos (' KMG', strtoupper($suffix)));
    }
    return $number;
}
like image 107
akond Avatar answered Oct 25 '22 18:10

akond