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

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

例如,我希望: 12 months变成 12.Every 6 months变成 61M变成 1,等等。

167384 次浏览

You can use preg_replace in this case;

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

$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 returns "123.099" in this case

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

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

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

Use \D to match non-digit characters.

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