Extract a single integer from a string

后端 未结 21 2531
一个人的身影
一个人的身影 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:12

    Since there is only 1 numeric value to isolate in your string, I would endorse and personally use filter_var() with FILTER_SANITIZE_NUMBER_INT.

    echo filter_var($string, FILTER_SANITIZE_NUMBER_INT);
    

    A whackier technique which works because there is only 1 numeric value AND the only characters that come before the integer are alphanumeric, colon, or spaces is to use ltrim() with a character mask then cast the remaining string as an integer.

    Demo

    $string = "In My Cart : 11 items";
    echo (int)ltrim($string, 'A..z: ');
    // 11
    

    If for some reason there was more than one integer value and you wanted to grab the first one, then regex would be a direct technique.

    Demo

    echo preg_match('/\d+/', $string, $m) ? $m[0] : '';
    

提交回复
热议问题