phpstringintegertext-extraction

Extract a single (unsigned) integer from a string


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 number 11.


Solution

  • You can use regex to extract all numeric characters from a string:

    $str = 'In My Cart : 11 12 items';
    preg_match_all('!\d+!', $str, $matches);
    print_r($matches);
    

    You can then concatenate them to make your integer:

    $integer = implode('', $matches[0]);