我想从一个包含数字和字母的字符串中提取数字,比如:
"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;
其他回答
这个脚本首先创建一个文件,将数字写入一行,如果得到的字符不是数字,则更改到下一行。最后,它再次把这些数字整理成一个列表。
string1 = "hello my name 12 is after 198765436281094and14 and 124de"
f= open("created_file.txt","w+")
for a in string1:
if a in ['1','2','3','4','5','6','7','8','9','0']:
f.write(a)
else:
f.write("\n" +a+ "\n")
f.close()
#desired_numbers=[x for x in open("created_file.txt")]
#print(desired_numbers)
k=open("created_file.txt","r")
desired_numbers=[]
for x in k:
l=x.rstrip()
print(len(l))
if len(l)==15:
desired_numbers.append(l)
#desired_numbers=[x for x in k if len(x)==16]
print(desired_numbers)
我们可以从它中提取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
$value = '25%';
Or
$value = '25.025$';
Or
$value = 'I am numeric 25';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
这将只返回数值
其他方式(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 )
如果你不知道数字的格式?Int或float,然后使用这个:
$string = '$125.22';
$string2 = '$125';
preg_match_all('/(\d+.?\d+)/',$string,$matches); // $matches[1] = 125.22
preg_match_all('/(\d+.?\d+)/',$string2,$matches); // $matches[1] = 125