PHP extract all whole numbers into an array

前端 未结 4 1116
清酒与你
清酒与你 2021-01-28 15:58

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 li

相关标签:
4条回答
  • 2021-01-28 16:17
    $str = '15 asdas 26 dasda 354 dasd 1';
    preg_match_all('/\d+/', $str, $matches);
    print_r($matches);
    
    0 讨论(0)
  • 2021-01-28 16:19

    See this Demo

    Solution 1 :

    This solution use is_numeric function :

    print_r(array_filter(split(" ", "15 asdas 26 dasda 354 dasd 1"),"is_numeric"));
    

    Solution 2 :

    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"));
    

    Solution 3 :

    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"));
    
    0 讨论(0)
  • 2021-01-28 16:25

    use preg_match: http://www.php.net/manual/en/function.preg-match.php

    check examples at site bottom.

    0 讨论(0)
  • 2021-01-28 16:43

    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]);
    
    0 讨论(0)
提交回复
热议问题