Extract a single integer from a string

后端 未结 21 2470
一个人的身影
一个人的身影 2020-11-21 23:33

I want to extract the digits from a string that contains numbers and letters like:

"In My Cart : 11 items"

I want to extract the nu

21条回答
  •  感情败类
    2020-11-22 00:04

    other way(unicode string even):

    $res = array();
    $str = 'test 1234 555 2.7 string ..... 2.2 3.3';
    $str = preg_replace("/[^0-9\.]/", " ", $str);
    $str = trim(preg_replace('/\s+/u', ' ', $str));
    $arr = explode(' ', $str);
    for ($i = 0; $i < count($arr); $i++) {
        if (is_numeric($arr[$i])) {
            $res[] = $arr[$i];
        }
    }
    print_r($res); //Array ( [0] => 1234 [1] => 555 [2] => 2.7 [3] => 2.2 [4] => 3.3 ) 
    

提交回复
热议问题