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:

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.

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!

Facebook Comments