PHP: How to extract numbers from the string

You can use regular expression of course. Other choice is to use the PHP filter_var() function.
See this example:

$array = array('car1',
 '20apples',
 'birds',
 'string 111 with spaces',
 'more 20 integers 5 in one string');

foreach ($array as $item) {
 $number = filter_var($item, FILTER_SANITIZE_NUMBER_INT);

 //print results
 var_dump($number);
}
As you can see, the result is string which contains only the digits from the original string.
string(1) "1"
string(2) "20"
string(0) ""
string(3) "111"
string(3) "205"

Comments