Extract a single (unsigned) integer from a string

Bizboss picture Bizboss · Jun 8, 2011 · Viewed 509k times · Source

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.

Answer

Daniel Bøndergaard picture Daniel Bøndergaard · Sep 25, 2012

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);