php 过滤掉php中字符串中的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4837278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter out numbers in a string in php
提问by Rami Dabain
assuming i have these texts 'x34' , '150px' , '650dpi' , 'e3r4t5' ... how can i get only numbers ? i mean i want 34 , 150 , 650 , 345 without any other character . i mean get the numbers this string has into one variable .
假设我有这些文本 'x34' 、 '150px' 、 '650dpi' 、 'e3r4t5' ......我怎么能只得到数字?我的意思是我想要 34 、 150 、 650 、 345 没有任何其他字符。我的意思是将这个字符串的数字放入一个变量中。
回答by Tim Cooper
$str = "e3r4t5";
$str_numbers_only = preg_replace("/[^\d]/", "", $str);
// $number = (int) $str;
回答by Abhishek Madhani
Sorry for joining the bandwagon late, rather than using Regex, I would suggest you use PHP's built in functions, which may be faster than Regex.
很抱歉加入这个潮流太晚,而不是使用 Regex,我建议您使用 PHP 的内置函数,它可能比 Regex 更快。
e.g. to get just numbers from the given string
例如从给定的字符串中只获取数字
<?php
$a = '!a-b.c3@j+dk9.0e8`~]\]2';
$number = str_replace(['+', '-'], '', filter_var($a, FILTER_SANITIZE_NUMBER_INT));
// Output is 390382
?>
To adhere to more strict standards for your question, I have updated my answer to give a better result.
为了对您的问题遵守更严格的标准,我更新了我的答案以提供更好的结果。
I have added str_replace, as FILTER_SANITIZE_NUMBER_FLOAT
or INT
flag will not strip +
and -
chars from the string, because they are part of PHP's exception rule.
我添加了 str_replace,因为FILTER_SANITIZE_NUMBER_FLOAT
orINT
标志不会从字符串中剥离+
和-
字符,因为它们是 PHP 异常规则的一部分。
Though it has made the filter bit long, but it's now has less chance of failing or giving you unexpected results, and this will be faster than REGEX.
虽然它使过滤器有点长,但它现在失败或给你意想不到的结果的机会更少,而且这将比 REGEX 更快。
Edit:
编辑:
1:Realized that with FILTER_SANITIZE_NUMBER_FLOAT
, PHP won't strip these characters optionally.,eE
, hence to get just pure numbers kindly use FILTER_SANITIZE_NUMBER_INT
1:意识到使用FILTER_SANITIZE_NUMBER_FLOAT
,PHP 不会选择性地去除这些字符.,eE
,因此为了获得纯数字,请使用FILTER_SANITIZE_NUMBER_INT
2:If you have a PHP version less than 5.4, then kindly use array('+', '-')
instead of the short array syntax ['+', '-']
.
2:如果您的 PHP 版本低于5.4,请使用array('+', '-')
短数组语法代替['+', '-']
。
回答by Gumbo
You can use a regular expression to remove any character that is not a digit:
您可以使用正则表达式删除任何不是数字的字符:
preg_replace('/\D/', '', $str)
Here the pattern \D
describes any character that is not a digit (complement to \d
).
这里的模式\D
描述了任何不是数字的字符(对 的补充\d
)。
回答by Haijerome
回答by nikc.org
Replace everything that isn't a number and use that value.
替换不是数字的所有内容并使用该值。
$str = "foo1bar2baz3";
$num = intval(preg_replace("/[^0-9]/", "", $str));
回答by Jasmeen
You could use the following function:
您可以使用以下功能:
function extract_numbers($string) {
preg_match_all('/([\d]+)/', $string, $match);
return $match;
}