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

"In My Cart : 11 items"

我想提取数字11。


当前回答

使用sscanf的替代解决方案:

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

其他回答

preg_replace('/[^0-9]/', '', $string);

这应该做得更好!

这个函数也将处理浮点数

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

使用preg_replace

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

其他方式(unicode字符串甚至):

$res = array();
$str = 'test 1234 555 2.7 string ..... 2.2 3.3';
$str = preg_replace("/[^0-9\.]/", " ", $str);
$str = trim(preg_replace('/\s+/u', ' ', $str));
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++) {
    if (is_numeric($arr[$i])) {
        $res[] = $arr[$i];
    }
}
print_r($res); //Array ( [0] => 1234 [1] => 555 [2] => 2.7 [3] => 2.2 [4] => 3.3 ) 

使用sscanf的替代解决方案:

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