Extract a single (unsigned) integer from a string

559,188

Solution 1

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

Solution 2

If you just want to filter everything other than the numbers out, the easiest is to use filter_var:

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);

Solution 3

preg_replace('/[^0-9]/', '', $string);

This should do better job!...

Solution 4

Using preg_replace:

$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;

Output: 1111111111

Solution 5

For floating numbers,

preg_match_all('!\d+\.?\d+!', $string ,$match);

Thanks for pointing out the mistake. @mickmackusa

Share:
559,188
Bizboss
Author by

Bizboss

Frontend focused full stack developer

Updated on September 10, 2021

Comments

  • Bizboss
    Bizboss almost 3 years

    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.