Reputation: 329
I have following string:
15 asdas 26 dasda 354 dasd 1
and all that i want is to extract all numbers from it into an array, so it will looks like this:
array(4) {
[0]=>
string(2) "15"
[1]=>
string(2) "26"
[2]=>
string(3) "354"
[3]=>
string(1) "1"
}
Is there a way in PHP to achieve it?
Upvotes: 0
Views: 93
Reputation: 13173
See this Demo
This solution use is_numeric function :
print_r(array_filter(split(" ", "15 asdas 26 dasda 354 dasd 1"),"is_numeric"));
This solution use your own function :
function is_number($var) { return !(0 == intval($var)); }
print_r(array_filter(split(" ", "15 asdas 26 dasda 354 dasd 1"),"is_number"));
To 5.3.0 and more, this solution use preg_split function :
print_r(array_filter(preg_split(" ", "15 asdas 26 dasda 354 dasd 1"),"is_numeric"));
Upvotes: 1
Reputation: 89
use preg_match: http://www.php.net/manual/en/function.preg-match.php
check examples at site bottom.
Upvotes: 1
Reputation: 5237
$str = '15 asdas 26 dasda 354 dasd 1';
preg_match_all('/\d+/', $str, $matches);
print_r($matches);
Upvotes: 1
Reputation: 42063
You can use preg_match_all()
:
$string = '15 asdas 26 dasda 354 dasd 1';
preg_match_all('/\b(\d+)\b/', $string, $numbers);
var_dump($numbers[1]);
Upvotes: 2