我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
当前回答
如果你不知道数字的格式?Int或float,然后使用这个:
$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
其他回答
$value = '25%';
Or
$value = '25.025$';
Or
$value = 'I am numeric 25';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
这将只返回数值
这个函数也将处理浮点数
$str = "Doughnuts, 4; doughnuts holes, 0.08; glue, 3.4";
$str = preg_replace('/[^0-9\.]/','-', $str);
$str = preg_replace('/(\-+)(\.\.+)/','-', $str);
$str = trim($str, '-');
$arr = explode('-', $str);
对于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;
}
你可以使用preg_match:
$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);