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

问题描述:

对我来说,最好的方法是什么?我应该使用正则表达式还是可以使用另一个内置的PHP函数?

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?

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

For example, I'd want: 12 months to become 12. Every 6 months to become 6, 1M to become 1, etc.

谢谢

您可以使用 preg_replace

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

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

$res return 6 in this case.

如果还希望包含小数点分隔符或千位分隔符,请检查以下示例:

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

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

在这种情况下,$ res返回"123.099"

$res returns "123.099" in this case

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

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,.]/"