Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 321
Ahmed Ala Dali Avatar asked Jun 08 '11 11:06

Ahmed Ala Dali


3 Answers

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);
like image 75
Daniel Bøndergaard Avatar answered Nov 08 '22 13:11

Daniel Bøndergaard


$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
like image 404
Gaurav Avatar answered Nov 08 '22 12:11

Gaurav


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

This should do better job!...

like image 363
Mahipalsinh Ravalji Avatar answered Nov 08 '22 11:11

Mahipalsinh Ravalji