从字符串中提取单个(无符号)整数
我想从包含数字和字母的字符串中提取数字,例如:
"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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
如果您只想过滤除数字以外的所有内容,最简单的方法是使用 filter_var:
If you just want to filter everything other than the numbers out, the easiest is to use filter_var:
您可以使用正则表达式从字符串中提取所有数字字符:
然后您可以将它们连接起来以形成整数:
You can use regex to extract all numeric characters from a string:
You can then concatenate them to make your integer:
这应该会做得更好!...
This should do better job!...
使用preg_replace:
输出:1111111111
Using
preg_replace
:Output: 1111111111
对于浮点数,
感谢您指出错误。 @米克马库萨
For floating numbers,
Thanks for pointing out the mistake. @mickmackusa
我不拥有这一切的功劳,但我必须分享它。此正则表达式将从字符串中获取数字,包括小数点/位数以及逗号:
/((?:[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)?
您可以使用 preg_match:
You can use preg_match:
以下示例输入字符串的最佳资源友好型解决方案:
最快:
filter_var
— 使用指定的过滤器过滤变量<前><代码>var_dump(
filter_var($string, FILTER_SANITIZE_NUMBER_INT)
); // 字符串(2) "11"
几乎是最快的:
str_replace
— 将所有出现的搜索字符串替换为替换字符串<前><代码>var_dump(
str_replace(array('在我的购物车中:','项目', 's'),"", $string)
); // 字符串(2) "11"
足够快:
preg_replace
— 执行正则表达式搜索和替换<前><代码>var_dump(
preg_replace("/[^0-9]/","",$string)
); // 字符串(2) "11"
但是,
str_replace
的简单性会提高速度,但即使是有限的用例preg_replace
也会比str_replace
或filter_var
更通用,preg_replace_callback
preg_replace_callback
可以在一次调用中进行多次替换filter_var
限制在 卫生选项The top resource-friendly solutions for the following sample input string:
Fastest:
filter_var
— Filters a variable with a specified filterAlmost the fastest:
str_replace
— Replace all occurrences of the search string with the replacement stringFast enough:
preg_replace
— Perform a regular expression search and replaceHowever
str_replace
cause speed, but even limited use casespreg_replace
is much more versatile thanstr_replace
orfilter_var
preg_replace_callback
preg_replace_callback
can do multiple replacements in one callfilter_var
limited in sanitation options使用 preg_replace
Using preg_replace
Or
Or
这将仅返回数值
Or
Or
This will return only the numeric value
由于您的字符串中只有 1 个需要隔离的数值,因此我赞同并个人将
filter_var()
与FILTER_SANITIZE_NUMBER_INT
一起使用。演示
一种更奇怪的技术,它之所以有效,是因为只有 1 个数字值和前面的唯一字符整数是字母、冒号或空格,方法是将
ltrim()
与字符掩码一起使用,然后将剩余的字符串转换为整数。演示
或者另一种前端修剪字符串的方法是使用
strpbrk() 和全数字字符掩码。 此页面专门介绍利用字符掩码的字符串函数,可能会更加清晰。
演示
如果由于某种原因有多个整数值并且您想获取第一个,那么正则表达式将是直接技术。
演示
演示
当然,如果字符串中只有一个数字,正如其他人所说,
preg_replace()
可以简单地销毁非数字字符。演示
sscanf()
如果您需要显式转换作为整数(或浮点数)的数字字符串。如果整数值可能/未知出现在字符串的开头,则在扫描输入字符串之前在其前面添加一个非数字字符。以下技术匹配前导非数字(并在%
之后使用*
忽略它们),然后匹配第一个出现的数字序列并将返回的子字符串转换为整数。演示
要采用此技术来提取浮点值,只需将
d
更改为f
即可。有关sscanf()
的(当前未记录的)赋值抑制功能的更多信息,请参阅 这个发布。Since there is only 1 numeric value to isolate in your string, I would endorse and personally use
filter_var()
withFILTER_SANITIZE_NUMBER_INT
.Demo
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
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
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
Demo
Of course, if there is only one number in the string, as others have stated,
preg_replace()
can simply destroy non-digital characters.Demo
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
To adapt this technique to extract a float value, just change the
d
tof
. For more information on the (currently undocumented) assignment suppression feature ofsscanf()
, see this post.您可以使用以下功能:
You can use following function:
在这种特定情况下,内爆中的第一个参数表示“用单个空格分隔 matches[0] 中的每个元素。” Implode 不会在第一个数字之前或最后一个数字之后放置空格(或无论您的第一个参数是什么)。
其他需要注意的是 $matches[0] 是存储找到的匹配项(与此正则表达式匹配)的数组的位置。
有关数组中其他索引的进一步说明,请参阅: http: //php.net/manual/en/function.preg-match-all.php
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
试试这个,使用 preg_replace
演示
try this,use preg_replace
DEMO
我们可以像演示一样从中提取 int
: http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398
we can extract int from it like
demo : http://sandbox.onlinephpfunctions.com/code/82d58b5983e85a0022a99882c7d0de90825aa398
按照此步骤,它将把字符串转换为数字
另一种方法:
Follow this step it will convert string to number
Another way to do it :
其他方式(甚至unicode字符串):
other way(unicode string even):
sscanf 的替代解决方案:
An alternative solution with sscanf:
根据您的用例,这也可能是一个选项:
尽管我同意正则表达式或
filter_var()
在所述情况下会更有用。Depending on your use case, this might also be an option:
Though I'd agree a regex or
filter_var()
would be more useful in the stated case.对于 utf8 字符串:
for utf8 str:
该函数还将处理浮点数
This functions will also handle the floating 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.