我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
当前回答
这不是我的功劳,但我必须分享它。这个正则表达式将从字符串中获取数字,包括小数点/位数,以及逗号:
/ ((? : [0-9] +) * [0-9] + (? : \ [0-9] +)? /
引自此处: PHP - regex -如何提取一个数字与十进制(点和逗号)从字符串(例如1,120.01)?
其他回答
顶级资源友好型解决方案
<?php
var $string = "In My Cart : 11 items";
?>
1. 最快:filter_var -使用指定的过滤器过滤变量
<?php
filter_var($string, FILTER_SANITIZE_NUMBER_INT); // string(2) "11"
?>
2. 几乎是最快的:str_replace—用替换字符串替换所有搜索字符串
<?php
str_replace(array('In My Cart : ',' item', 's'),"", $string); // string(2) "11"
?>
3.足够快:preg_replace -执行正则表达式搜索和替换
<?php
preg_replace("/[^0-9]/","",$string); // string(2) "11"
?>
然而
str_replace的简单性导致速度加快,但用例也有限 Preg_replace比str_replace或filter_var更通用 相反,可以使用preg_replace_callback函数指定要替换的内容 使用preg_replace_callback可以在一次调用中执行多个替换 Filter_var在环卫选项中受限
preg_replace('/[^0-9]/', '', $string);
这应该做得更好!
试试这个,使用preg_replace
$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
DEMO
对于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_replace
$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;