PHP preg 替换只允许数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7688844/
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-26 03:11:18 来源:igfitidea点击:
PHP preg replace only allow numbers
提问by Ryan
How can I modify this existing preg_replace to only allow numbers?
如何修改这个现有的 preg_replace 以只允许数字?
function __cleanData($c)
{
return preg_replace("/[^A-Za-z0-9]/", "",$c);
}
回答by lonesomeday
I think you're saying you want to remove all non-numeric characters. If so, \D
means "anything that isn't a digit":
我认为您是说要删除所有非数字字符。如果是这样,则\D
表示“任何不是数字的东西”:
preg_replace('/\D/', '', $c)
回答by qbert220
Try this:
尝试这个:
return preg_replace("/[^0-9]/", "",$c);
回答by oezi
This should do what you want:
这应该做你想做的:
preg_replace("/[^0-9]/", "",$c);
回答by Danon
You could also use T-Regx library:
您还可以使用T-Regx 库:
pattern('\D')->remove($c)
T-Regx also:
T-Regx 还:
- Throws exceptions on fail (not
false
,null
or warnings) - Has automatic delimiters (delimiters are not required!)
- Has a lot cleaner api
- 失败时抛出异常(不是
false
,null
或警告) - 具有自动分隔符(不需要分隔符!)
- 有很多更干净的api