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
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
preg_replace('/[^0-9]/', '', $string);
This should do better job!...
try this,use preg_replace
$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
DEMO
For floating numbers,
preg_match_all('!\d+\.?\d+!', $string ,$match);
Thanks for pointing out the mistake. @mickmackusa
for utf8 str:
function unicodeStrDigits($str) {
$arr = array();
$sub = '';
for ($i = 0; $i < strlen($str); $i++) {
if (is_numeric($str[$i])) {
$sub .= $str[$i];
continue;
} else {
if ($sub) {
array_push($arr, $sub);
$sub = '';
}
}
}
if ($sub) {
array_push($arr, $sub);
}
return $arr;
}
If you don't know which format the number is? int or floating, then use this :
$string = '$125.22';
$string2 = '$125';
preg_match_all('/(\d+.?\d+)/',$string,$matches); // $matches[1] = 125.22
preg_match_all('/(\d+.?\d+)/',$string2,$matches); // $matches[1] = 125