PHP: Get numbers from a string.

This is a short PHP tutorial on how to get numbers from a string. To do this, we will extract the numbers using the function preg_match_all.

The preg_match_all function.

The preg_match_all function allows us to match certain characters using regular expressions. In our case, we want to match numerical values.

Getting integers / whole numbers from a string.

If you’re looking to extract whole numbers from a string, then you can use the following piece of code:

//A string containing two integer values.
$str = 'There are 330 days until Christmas. It is currently 12PM.';

//Extract the numbers using the preg_match_all function.
preg_match_all('!\d+!', $str, $matches);

//Any matches will be in our $matches array

If you run the code above, you will get the following result:

Extracting numbers from a string in PHP.

Extracting numbers from a string in PHP.

As you can see, we were able to extract the integers from our string by using PHP’s preg_match_all function.

But what if we also want to be able to extract decimal numbers?

Extracting decimal numbers.

To extract decimal and float numbers from a string, we will have to use a different regular expression. Otherwise, our code in the previous example will split the numbers up.

//A string that contains both an integer and a decimal number.
$string = 'A 2 euro coin weighs 8.5 grams.';

//Extract the numbers using the preg_match_all function.
preg_match_all('!\d+\.*\d*!', $string, $matches);

//var_dump the result

In the example above, we were able to extract both the whole number and the decimal number. If you var_dump the array, you will see the following result:

Extract decimals.

A var_dump of our $matches array.

As you can see, we managed to extract both the 2 and the 8.5 from our text.

Hopefully, you found the code above useful!