PHP - 从字符串中删除所有非数字字符[重复]

时间:2022-04-19 09:33:58

This question already has an answer here:

这个问题在这里已有答案:

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 months to become 12. Every 6 months to become 6, 1M to become 1, etc.

例如,我想要:12个月变为12个。每6个月变为6个,1M变为1个等等。

Thank you

谢谢

2 个解决方案

#1


39  

You can use preg_replace in 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,。] /”

#2


22  

Use \D to match non-digit characters.

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

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

#1


39  

You can use preg_replace in 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,。] /”

#2


22  

Use \D to match non-digit characters.

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

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