我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
当前回答
对于浮点数,
preg_match_all('!\d+\.?\d+!', $string ,$match);
谢谢你指出错误。@mickmackusa
其他回答
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
使用preg_replace:
$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;
输出:1111111111
使用sscanf的替代解决方案:
$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');
对于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;
}
根据你的用例,这也是一种选择:
$str = 'In My Cart : 11 items';
$num = '';
for ($i = 0; $i < strlen($str); $i++) {
if (is_numeric($str[$i])) {
$num .= $str[$i];
}
}
echo $num; // 11
尽管我同意regex或filter_var()在上述情况下更有用。