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

"In My Cart : 11 items"

我想提取数字11。


当前回答

使用sscanf的替代解决方案:

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

其他回答

这个函数也将处理浮点数

$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);
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

我们可以从它中提取int

$string = 'In My Car_Price : 50660.00';

echo intval(preg_replace('/[^0-9.]/','',$string));  # without number format   output: 50660
echo number_format(intval(preg_replace('/[^0-9.]/','',$string)));  # with number format  output :50,660

演示:http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398

使用preg_replace:

$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;

输出:1111111111

按照这一步,它将把字符串转换为数字

$value = '$0025.123';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
settype($onlyNumeric,"float");

$result=($onlyNumeric+100);
echo $result;

另一种说法是:

$res = preg_replace("/[^0-9.]/", "", "$15645623.095605659");