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 nu
Since there is only 1 numeric value to isolate in your string, I would endorse and personally use filter_var()
with FILTER_SANITIZE_NUMBER_INT
.
echo filter_var($string, FILTER_SANITIZE_NUMBER_INT);
A whackier technique which works because there is only 1 numeric value AND the only characters that come before the integer are alphanumeric, colon, or spaces is to use ltrim()
with a character mask then cast the remaining string as an integer.
Demo
$string = "In My Cart : 11 items";
echo (int)ltrim($string, 'A..z: ');
// 11
If for some reason there was more than one integer value and you wanted to grab the first one, then regex would be a direct technique.
Demo
echo preg_match('/\d+/', $string, $m) ? $m[0] : '';