我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
我想从一个包含数字和字母的字符串中提取数字,比如:
"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);
使用preg_replace:
$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;
输出:1111111111
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
使用sscanf的替代解决方案:
$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');
preg_replace('/[^0-9]/', '', $string);
这应该做得更好!