问题描述
对我来说,最好的方法是什么?我应该使用正则表达式还是可以使用另一个内置的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
变为6
,1M
变为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,.]/"
这篇关于PHP-从字符串中删除所有非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!