PHP - 从字符串中删除所有非数字字符

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

PHP - remove all non-numeric characters from a string

phpstring

提问by b85411

What is the best way for me to do this? Should I use regex or is there another in-built PHP function I can use?

我这样做的最佳方法是什么?我应该使用正则表达式还是可以使用另一个内置的 PHP 函数?

For example, I'd want: 12 monthsto become 12. Every 6 monthsto become 6, 1Mto become 1, etc.

例如,我想要:12 months成为12. Every 6 months成为61M成为1,等等。

Thank you

谢谢

回答by pguetschow

You can use preg_replacein this case;

在这种情况下,您可以使用preg_replace

$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );

$res return 6 in this case.

在这种情况下,$res 返回 6。

If want also to include decimal separator or thousand separator check this example:

如果还想包含小数分隔符或千位分隔符,请检查此示例:

$res = preg_replace("/[^0-9.]/", "", "$ 123.099");

$res returns "123.099" in this case

在这种情况下 $res 返回“123.099”

Include period as decimal separator or thousand separator: "/[^0-9.]/"

包括句点作为小数点分隔符或千位分隔符:“/[^0-9.]/”

Include coma as decimal separator or thousand separator: "/[^0-9,]/"

包括逗号作为小数点分隔符或千位分隔符:"/[^0-9,]/"

Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"

包括句点和逗号作为小数点分隔符和千位分隔符:“/[^0-9,.]/”

回答by Avinash Raj

Use \Dto match non-digit characters.

使用\D匹配非数字字符。

preg_replace('~\D~', '', $str);