PHP 正则表达式 - 仅过滤器编号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5474088/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:33:34  来源:igfitidea点击:

PHP regular expression - filter number only

phpregex

提问by user398341

I know this might sound as really dummy question, but I'm trying to ensure that the provided string is of a number / decimal format to use it later on with PHP's number_format() function.

我知道这听起来可能是一个非常愚蠢的问题,但我试图确保提供的字符串是数字/十进制格式,以便稍后与 PHP 的 number_format() 函数一起使用。

How would I do it - say someone is typing 15:00 into the text field - what regular expression and php function should I use to remove the colon from it and make it only return the valid characters.

我该怎么做 - 假设有人在文本字段中输入 15:00 - 我应该使用什么正则表达式和 php 函数来从中删除冒号并使其只返回有效字符。

preg_match() returns array - so I can't pass the result to number_format() unless I implode() it or something like this.

preg_match() 返回数组 - 所以我不能将结果传递给 number_format() 除非我 implode() 它或类似的东西。

Your help would be very much appreciated.

您的帮助将不胜感激。

回答by buley

Using is_numericor intvalis likely the best way to validate a number here, but to answer your question you could try using preg_replaceinstead. This example removes all non-numeric characters:

在这里使用is_numericintval可能是验证数字的最佳方法,但要回答您的问题,您可以尝试使用preg_replace代替。此示例删除所有非数字字符:

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

回答by netcoder

To remove anything that is not a number:

要删除任何不是数字的内容:

$output = preg_replace('/[^0-9]/', '', $input);

Explanation:

解释:

  • [0-9]matches any number between 0 and 9 inclusively.
  • ^negates a []pattern.
  • So, [^0-9]matches anything that is not a number, and since we're using preg_replace, they will be replaced by nothing ''(second argument of preg_replace).
  • [0-9]匹配 0 到 9 之间的任意数字。
  • ^否定一个[]模式。
  • 因此,[^0-9]匹配任何不是数字的东西,因为我们使用的是preg_replace,所以它们将被替换为空''( 的第二个参数preg_replace)。

回答by SileNT

You can try that one:

你可以试试那个:

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

Cheers.

干杯。

回答by Headshota

use built in php function is_numericto check if the value is numeric.

使用内置的 php 函数is_numeric来检查值是否为数字。

回答by Kyle Coots

You could do something like this if you want only whole numbers.

如果你只想要整数,你可以做这样的事情。

function make_whole($v){
    $v = floor($v);
    if(is_numeric($v)){
      echo (int)$v;
      // if you want only positive whole numbers
      //echo (int)$v = abs($v);
    }
}

回答by Samuel

Another way to get only the numbers in a regex string is as shown below:

另一种仅获取正则表达式字符串中数字的方法如下所示:

$output = preg_replace("/\D+/", "", $input);