我想从一个包含数字和字母的字符串中提取数字,比如:

"In My Cart : 11 items"

我想提取数字11。


当前回答

使用preg_replace

$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;

其他回答

如果你只想过滤除数字以外的所有内容,最简单的方法是使用filter_var:

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);

这个函数也将处理浮点数

$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);

使用sscanf的替代解决方案:

$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');

你可以使用以下函数:

function extract_numbers($string)
{
   preg_match_all('/([\d]+)/', $string, $match);

   return $match[0];
}

这不是我的功劳,但我必须分享它。这个正则表达式将从字符串中获取数字,包括小数点/位数,以及逗号:

/ ((? : [0-9] +) * [0-9] + (? : \ [0-9] +)? /

引自此处: PHP - regex -如何提取一个数字与十进制(点和逗号)从字符串(例如1,120.01)?