从字符串中提取单个(无符号)整数

发布于 2024-11-14 14:06:54 字数 109 浏览 3 评论 0原文

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

"In My Cart : 11 items"

我想提取数字11

I want to extract the digits from a string that contains numbers and letters like:

"In My Cart : 11 items"

I want to extract the number 11.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

迷爱 2024-11-21 14:06:54

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

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);

If you just want to filter everything other than the numbers out, the easiest is to use filter_var:

$str = 'In My Cart : 11 items';
$int = (int) filter_var($str, FILTER_SANITIZE_NUMBER_INT);
锦爱 2024-11-21 14:06:54

您可以使用正则表达式从字符串中提取所有数字字符:

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

然后您可以将它们连接起来以形成整数:

$integer = implode('', $matches[0]);

You can use regex to extract all numeric characters from a string:

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);

You can then concatenate them to make your integer:

$integer = implode('', $matches[0]);
愛放△進行李 2024-11-21 14:06:54
preg_replace('/[^0-9]/', '', $string);

这应该会做得更好!...

preg_replace('/[^0-9]/', '', $string);

This should do better job!...

扶醉桌前 2024-11-21 14:06:54

使用preg_replace:

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

输出:1111111111

Using preg_replace:

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

Output: 1111111111

爱格式化 2024-11-21 14:06:54

对于浮点数,

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

感谢您指出错误。 @米克马库萨

For floating numbers,

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

Thanks for pointing out the mistake. @mickmackusa

蓝海似她心 2024-11-21 14:06:54

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

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

引用自此处:
php - 正则表达式 - 如何从字符串中提取带小数的数字(点和逗号)(例如 1,120.01)?

I do not own the credit for this, but I just have to share it. This regex will get numbers from a string, including decimal points/places, as well as commas:

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

Cited from here:
php - regex - how to extract a number with decimal (dot and comma) from a string (e.g. 1,120.01)?

白色秋天 2024-11-21 14:06:54

您可以使用 preg_match

$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);

You can use preg_match:

$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);
做个少女永远怀春 2024-11-21 14:06:54

以下示例输入字符串的最佳资源友好型解决方案

$string = "In My Cart : 11 items";
  1. 最快:filter_var使用指定的过滤器过滤变量

    <前><代码>var_dump(
    filter_var($string, FILTER_SANITIZE_NUMBER_INT)
    ); // 字符串(2) "11"

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

    <前><代码>var_dump(
    str_replace(array('在我的购物车中:','项目', 's'),"", $string)
    ); // 字符串(2) "11"

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

    <前><代码>var_dump(
    preg_replace("/[^0-9]/","",$string)
    ); // 字符串(2) "11"

但是,

The top resource-friendly solutions for the following sample input string:

$string = "In My Cart : 11 items";
  1. Fastest: filter_varFilters a variable with a specified filter

    var_dump(
        filter_var($string, FILTER_SANITIZE_NUMBER_INT)
    ); // string(2) "11"
    
  2. Almost the fastest: str_replace — Replace all occurrences of the search string with the replacement string

    var_dump(
        str_replace(array('In My Cart : ',' item', 's'),"", $string)
    ); // string(2) "11"
    
  3. Fast enough: preg_replacePerform a regular expression search and replace

    var_dump(
        preg_replace("/[^0-9]/","",$string)
    ); // string(2) "11"
    

However

  • the simplicity of str_replace cause speed, but even limited use cases
  • preg_replace is much more versatile than str_replace or filter_var
  • instead is possible to use a function to specify what to replace using preg_replace_callback
  • with preg_replace_callback can do multiple replacements in one call
  • filter_var limited in sanitation options
年华零落成诗 2024-11-21 14:06:54

使用 preg_replace

$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;

Using preg_replace

$str = 'In My Cart : 11 12 items';
$str = preg_replace('/\D/', '', $str);
echo $str;
热情消退 2024-11-21 14:06:54
$value = '25%';

Or

$value = '25.025

Or

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

这将仅返回数值

;

Or

这将仅返回数值

$value = '25%';

Or

$value = '25.025

Or

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

This will return only the numeric value

;

Or

This will return only the numeric value

躲猫猫 2024-11-21 14:06:54
  1. 由于您的字符串中只有 1 个需要隔离的数值,因此我赞同并个人将 filter_var()FILTER_SANITIZE_NUMBER_INT 一起使用。

    演示

    var_export(filter_var($string, FILTER_SANITIZE_NUMBER_INT));
    //'11'
    
  2. 一种更奇怪的技术,它之所以有效,是因为只有 1 个数字值和前面的唯一字符整数是字母、冒号或空格,方法是将 ltrim() 与字符掩码一起使用,然后将剩余的字符串转换为整数。

    演示

    var_export((int) ltrim($string, 'A..z: '));
                              // 或 ':..z '(ASCII 表和空格上的冒号到 z)
    // 11
    
  3. 或者另一种前端修剪字符串的方法是使用 strpbrk() 和全数字字符掩码。 此页面专门介绍利用字符掩码的字符串函数,可能会更加清晰。

    演示

    var_export((int) strpbrk($string, '0123456789'));
    // 11
    

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

    演示

    var_export(preg_match('/\d+/', $string, $m) ? $m[0] : '');
    //'11'
    

    演示

    var_export(preg_replace('/\D*(\d+).*/', '$1', $string));
    //'11'
    

    当然,如果字符串中只有一个数字,正如其他人所说,preg_replace() 可以简单地销毁非数字字符。
    演示

    var_export(preg_replace('/\D+/', '', $string));
    //'11'
    
  5. sscanf() 如果您需要显式转换作为整数(或浮点数)的数字字符串。如果整数值可能/未知出现在字符串的开头,则在扫描输入字符串之前在其前面添加一个非数字字符。以下技术匹配前导非数字(并在 % 之后使用 * 忽略它们),然后匹配第一个出现的数字序列并将返回的子字符串转换为整数。

    演示

    var_export(sscanf(' ' . $string, '%*[^0-9]%d')[0]);
    // 11
    

    要采用此技术来提取浮点值,只需将 d 更改为 f 即可。有关 sscanf() 的(当前未记录的)赋值抑制功能的更多信息,请参阅 这个发布

  1. Since there is only 1 numeric value to isolate in your string, I would endorse and personally use filter_var() with FILTER_SANITIZE_NUMBER_INT.

    Demo

    var_export(filter_var($string, FILTER_SANITIZE_NUMBER_INT));
    // '11'
    
  2. A whackier technique which works because there is only 1 numeric value AND the only characters that come before the integer are letters, colons, or spaces is to use ltrim() with a character mask then cast the remaining string as an integer.

    Demo

    var_export((int) ltrim($string, 'A..z: '));
                              // or ':..z ' (colon to z on ascii table and space)
    // 11
    
  3. Or another way to front-trim the string would be with strpbrk() and an all-digital character mask. This page dedicated to string functions which leverage character masks may give additional clarity.

    Demo

    var_export((int) strpbrk($string, '0123456789'));
    // 11
    
  4. If for some reason there was more than one integer value and you wanted to grab the first one, then regex would be a direct technique.

    Demo

    var_export(preg_match('/\d+/', $string, $m) ? $m[0] : '');
    // '11'
    

    Demo

    var_export(preg_replace('/\D*(\d+).*/', '$1', $string));
    // '11'
    

    Of course, if there is only one number in the string, as others have stated, preg_replace() can simply destroy non-digital characters.
    Demo

    var_export(preg_replace('/\D+/', '', $string));
    // '11'
    
  5. sscanf() is rather handy if you need to explicitly cast the numeric string as an integer (or float). If it is possible/unknown for the integer value to occur at the start of the string, then prepend a non-numeric character to the input string before scanning it. The following technique matches leading non-digits (and ignores them with * after the %), then matches the first occurring sequence of digits and casts the returned substring as an integer.

    Demo

    var_export(sscanf(' ' . $string, '%*[^0-9]%d')[0]);
    // 11
    

    To adapt this technique to extract a float value, just change the d to f. For more information on the (currently undocumented) assignment suppression feature of sscanf(), see this post.

行至春深 2024-11-21 14:06:54

您可以使用以下功能:

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

   return $match[0];
}

You can use following function:

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

   return $match[0];
}
生活了然无味 2024-11-21 14:06:54
preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

在这种特定情况下,内爆中的第一个参数表示“用单个空格分隔 matches[0] 中的每个元素。” Implode 不会在第一个数字之前或最后一个数字之后放置空格(或无论您的第一个参数是什么)。

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

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

preg_match_all('!\d+!', $some_string, $matches);
$string_of_numbers = implode(' ', $matches[0]);

The first argument in implode in this specific case says "separate each element in matches[0] with a single space." Implode will not put a space (or whatever your first argument is) before the first number or after the last number.

Something else to note is $matches[0] is where the array of matches (that match this regular expression) found are stored.

For further clarification on what the other indexes in the array are for see: http://php.net/manual/en/function.preg-match-all.php

清秋悲枫 2024-11-21 14:06:54

试试这个,使用 preg_replace

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

演示

try this,use preg_replace

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

DEMO

滥情哥ㄟ 2024-11-21 14:06:54

我们可以像演示一样从中提取 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

we can extract int from it like

$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

demo : http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398

困倦 2024-11-21 14:06:54

按照此步骤,它将把字符串转换为数字

$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");

Follow this step it will convert string to number

$value = '$0025.123';
$onlyNumeric = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
settype($onlyNumeric,"float");

$result=($onlyNumeric+100);
echo $result;

Another way to do it :

$res = preg_replace("/[^0-9.]/", "", "$15645623.095605659");
删除→记忆 2024-11-21 14:06:54

其他方式(甚至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 ) 

other way(unicode string even):

$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 ) 
滥情空心 2024-11-21 14:06:54

sscanf 的替代解决方案:

$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');

An alternative solution with sscanf:

$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');
冷弦 2024-11-21 14:06:54

如果您不知道号码是什么格式? 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

If you don't know which format the number is? int or floating, then use this :

$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
物价感观 2024-11-21 14:06:54

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

$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() 在所述情况下会更有用。

Depending on your use case, this might also be an option:

$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

Though I'd agree a regex or filter_var() would be more useful in the stated case.

那请放手 2024-11-21 14:06:54

对于 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;
}

for utf8 str:

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;
}
恰似旧人归 2024-11-21 14:06:54

该函数还将处理浮点数

$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);

This functions will also handle the floating numbers

$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);
音盲 2024-11-21 14:06:54

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

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)

This script creates a file at first , write numbers to a line and changes to a next line if gets a character other than number. At last, again it sorts out the numbers to a list.

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文