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 1:
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 2:
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
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