我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
我想从一个包含数字和字母的字符串中提取数字,比如:
"In My Cart : 11 items"
我想提取数字11。
当前回答
使用sscanf的替代解决方案:
$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');
其他回答
你可以使用preg_match:
$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);
试试这个,使用preg_replace
$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;
DEMO
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
其他方式(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 )
按照这一步,它将把字符串转换为数字
$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");