删除除数字以外的所有内容的 PHP 代码

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

PHP code to remove everything but numbers

phpregexstring

提问by jeffkee

I'm trying to remove everything from a string but just numbers (0-9).

我试图从字符串中删除所有内容,但只删除数字(0-9)。

I thought this would work..

我以为这会奏效..

echo preg_replace("[^0-9]","",'604-619-5135');

But it echos "604-619-5135". What am I missing???

但它与“604-619-5135”相呼应。我错过了什么???

回答by Chris Eberle

Try this:

尝试这个:

preg_replace('/[^0-9]/', '', '604-619-5135');

preg_replace uses PCREs which generally start and end with a /.

preg_replace 使用通常以/.

回答by Navneil Naicker

This is for future developers, you can also try this. Simple too

这是为未来的开发者准备的,你也可以试试这个。也简单

echo preg_replace('/\D/', '', '604-619-5135');

回答by SBerg413

You would need to enclose the pattern in a delimiter - typically a slash (/) is used. Try this:

您需要将模式括在分隔符中 - 通常使用斜杠 (/)。尝试这个:

echo preg_replace("/[^0-9]/","",'604-619-5135');

回答by Alp Altunel

a much more practical way for those who do not want to use regex:

对于那些不想使用正则表达式的人来说,这是一种更实用的方法:

$data = filter_var($data, FILTER_SANITIZE_NUMBER_INT);

note: it works with phone numbers too.

注意:它也适用于电话号码。