In PHP, you can extract numbers from a string using regular expressions and the preg_match_all()
function. Here's an example of how to extract all numbers from a string:
$my_string = "There are 15 Oranges and 3 Bananas.";
preg_match_all('/[0-9]+/', $my_string , $matches);
print_r($matches[0]);
This will output:
Array ( [0] => 15 [1] => 3 )
Explanation:
/[0-9]+/
searches for one or more consecutive digits.preg_match_all()
function searches the string for all occurrences of the regular expression and stores the matches in the $matches
array.print_r()
function is used to display the contents of the array.You can also use the preg_replace()
function to remove non-numeric characters from a string and keep only the numbers:
$string = "There are 15 Oranges and 3 Bananas.";
$numbers = preg_replace('/D/', '', $string);
echo $numbers;
This will output:
15 3
Explanation:
/D/
matches any non-digit character.preg_replace()
function replaces all non-digit characters with an empty string, effectively removing them from the string.There is one another way to however it's not that reliable like above two options. We can use filter_var()
PHP built-in function to extract int from string.
$string = "There are 15 Oranges and 3 Bananas.";
// extract numbers from string
$my_int = (int)filter_var($string ,FILTER_SANITIZE_NUMBER_INT);
echo $my_int;
This will output:
153