我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
当前回答
这不是我的功劳,但我必须分享它。这个正则表达式将从字符串中获取数字,包括小数点/位数,以及逗号:
/ ((? : [0-9] +) * [0-9] + (? : \ [0-9] +)? /
引自此处: PHP - regex -如何提取一个数字与十进制(点和逗号)从字符串(例如1,120.01)?
其他回答
preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);
在本例中,implode中的第一个参数表示“用单个空格分隔匹配[0]中的每个元素。”Implode不会在第一个数字之前或最后一个数字之后放置空格(或任何你的第一个参数)。
另外需要注意的是$matches[0]是存储匹配数组(匹配此正则表达式)的地方。
有关数组中其他索引的进一步说明,请参阅:http://php.net/manual/en/function.preg-match-all.php
你可以使用preg_match:
$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);
preg_replace('/[^0-9]/', '', $string);
这应该做得更好!
使用preg_replace:
$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;
输出:1111111111
使用sscanf的替代解决方案:
$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');