375

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

"In My Cart : 11 items"

我想提取数字11

4

23 回答 23

607

如果您只想过滤除数字以外的所有内容,最简单的方法是使用filter_var

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
于 2012-09-25T11:53:04.723 回答
399
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
于 2011-06-08T11:56:00.460 回答
352
preg_replace('/[^0-9]/', '', $string);

这应该做得更好!...

于 2013-02-09T14:48:03.797 回答
95

使用preg_replace

$str = '(111) 111-1111';
$str = preg_replace('/\D/', '', $str);
echo $str;

输出:1111111111

于 2014-06-03T04:38:44.340 回答
25

对于浮点数,

preg_match_all('!\d+\.?\d+!', $string ,$match);

感谢您指出错误。@mickmackusa

于 2013-03-20T13:30:59.257 回答
13

我不拥有这方面的功劳,但我只需要分享它。此正则表达式将从字符串中获取数字,包括小数点/位以及逗号:

/((?:[0-9]+,)*[0-9]+(?:\.[0-9]+)?)/

从这里引用:
php - regex - 如何从字符串(例如 1,120.01)中提取带小数点(点和逗号)的数字?

于 2015-02-06T23:51:16.530 回答
11

您可以使用preg_match

$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);
于 2011-06-08T11:56:45.720 回答
10

使用preg_replace

$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;
于 2013-02-17T16:37:30.970 回答
7
$value = '25%';

或者

$value = '25.025$';

或者

$value = 'I am numeric 25';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

这将只返回数值

于 2019-01-08T05:07:36.393 回答
6

您可以使用以下功能:

function extract_numbers($string)
{
   preg_match_all('/([\d]+)/', $string, $match);

   return $match[0];
}
于 2013-10-22T06:19:29.797 回答
4
preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

在这种特定情况下, implode 中的第一个参数表示“用一个空格分隔 match[0] 中的每个元素”。Implode 不会在第一个数字之前或最后一个数字之后放置空格(或任何您的第一个参数)。

还要注意的是 $matches[0] 是存储找到的匹配数组(匹配此正则表达式)的位置。

有关数组中其他索引的进一步说明,请参见: http: //php.net/manual/en/function.preg-match-all.php

于 2015-10-22T23:57:13.467 回答
4

试试这个,使用preg_replace

$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;

演示

于 2016-09-09T14:09:26.277 回答
4

顶级资源友好型解决方案

<?php
    var $string = "In My Cart : 11 items";
?>

1. 最快:filter_var——用指定的过滤器过滤一个变量

<?php
    filter_var($string, FILTER_SANITIZE_NUMBER_INT); // string(2) "11"
?>

2. 几乎是最快的:str_replace——用替换字符串替换所有出现的搜索字符串

<?php
    str_replace(array('In My Cart : ',' item', 's'),"", $string); // string(2) "11"
?>

3. 足够快:preg_replace——执行正则表达式搜索和替换

<?php
    preg_replace("/[^0-9]/","",$string); // string(2) "11"
?>

然而

  • 原因速度的简单性str_replace,但即使是有限的用例
  • preg_replace比或多才多艺_str_replacefilter_var
  • 相反,可以使用一个函数来指定要替换的内容preg_replace_callback
  • withpreg_replace_callback可以在一次调用中进行多次替换
  • filter_var卫生选择有限
于 2021-09-09T23:22:11.143 回答
3

我们可以从中提取 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

于 2019-01-15T10:21:13.450 回答
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");
于 2019-04-21T23:57:27.823 回答
2

由于您的字符串中只有 1 个数值要隔离,因此我赞同并亲自使用filter_var()with FILTER_SANITIZE_NUMBER_INT

echo filter_var($string, FILTER_SANITIZE_NUMBER_INT);

由于只有一个数值并且整数之前的唯一字符是字母数字、冒号或空格而起作用的一种更奇葩的技术是ltrim()与字符掩码一起使用,然后将剩余的字符串转换为整数。

演示

$string = "In My Cart : 11 items";
echo (int)ltrim($string, 'A..z: ');
// 11

如果由于某种原因有多个整数值并且您想获取第一个整数值,那么正则表达式将是一种直接的技术。

演示

echo preg_match('/\d+/', $string, $m) ? $m[0] : '';
于 2020-11-21T12:44:27.213 回答
0

其他方式(甚至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 ) 
于 2017-10-08T19:54:45.577 回答
0

sscanf 的替代解决方案:

$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');
于 2021-01-18T12:02:59.463 回答
-1

根据您的用例,这也可能是一个选项:

$str = 'In My Cart : 11 items';
$num = '';

for ($i = 0; $i < strlen($str); $i++) {

    if (is_numeric($str[$i])) {
        $num .= $str[$i];
    }
}

echo $num; // 11

虽然我同意正则表达式或者filter_var()在所述情况下会更有用。

于 2017-09-12T11:34:30.730 回答
-1

对于 utf8 字符串:

function unicodeStrDigits($str) {
    $arr = array();
    $sub = '';
    for ($i = 0; $i < strlen($str); $i++) { 
        if (is_numeric($str[$i])) {
            $sub .= $str[$i];
            continue;
        } else {
            if ($sub) {
                array_push($arr, $sub);
                $sub = '';
            }
        }
    }

    if ($sub) {
        array_push($arr, $sub); 
    }

    return $arr;
}
于 2017-10-05T19:26:57.323 回答
-1

如果您不知道数字是哪种格式?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
于 2018-09-24T19:15:33.223 回答
-1

此函数还将处理浮点数

$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);
于 2018-11-04T20:09:43.837 回答
-2

该脚本首先创建一个文件,将数字写入一行,如果获得数字以外的字符,则更改为下一行。最后,它再次将数字整理到一个列表中。

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)
于 2019-11-03T05:37:55.263 回答