This article demonstrates how to extract numbers from a string in PHP.

1. Using preg_replace() function

The idea is to identify all non-numeric characters in a string, and replace them with an empty string (""). In PHP, this can be done using the preg_replace() function. You can use the regex \D+ or [^0-9]+ to match one or more non-numeric characters, which can be easily modified to extract any additional characters from the string (like +, -, ., ,):

Download  Run Code

 
You can use the preg_match_all() function to get an array of all matches, as illustrated below. Here, \d+ matches one or more numeric characters.

Download  Run Code

2. Using filter_var() function

PHP has a built-in function called filter_var() that filters a variable with a specified filter. The FILTER_SANITIZE_NUMBER_FLOAT filter removes all characters from the string except digits, plus, and minus, and optionally eE. This filter will also remove the decimal character (.) unless FILTER_FLAG_ALLOW_FRACTION flag is specified. You may also use the FILTER_SANITIZE_NUMBER_INT which also removes all characters from the string except digits and +/-, but doesn’t accept any flag.

Download  Run Code

 
Note that both the above solutions preserve all plus, minus, and decimal signs. For example, the string "X--5.2" returns "Y--5.2". For example,

Download  Run Code

That’s all about extracting numbers from a string in PHP.