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

"In My Cart : 11 items"

我想提取数字11。


当前回答

你可以使用以下函数:

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

   return $match[0];
}

其他回答

对于浮点数,

preg_match_all('!\d+\.?\d+!', $string ,$match);

谢谢你指出错误。@mickmackusa

这个函数也将处理浮点数

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

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

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

你可以使用preg_match:

$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);

使用preg_replace

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