php 从字符串中去除所有字符,留下数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2118000/
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
stripping out all characters from a string, leaving numbers
提问by dotty
Hay, i have a string like this:
嘿,我有一个这样的字符串:
v8gn5.8gnr4nggb58gng.g95h58g.n48fn49t.t8t8t57
I want to strip out all the characters leaving just numbers (and .s)
我想去掉所有字符,只留下数字(和 .s)
Any ideas how to do this? Is there a function prebuilt?
任何想法如何做到这一点?有预建的功能吗?
thanks
谢谢
回答by Don
$str = preg_replace('/[^0-9.]+/', '', $str);
replace substrings that do not consist of digits or . with nothing.
替换不包含数字或 . 一无所有。
回答by Ionu? G. Stan
preg_replace('/[^0-9.]/', '', $string);
回答by Juraj Blahunka
$input = 'some str1ng 234';
$newString = preg_replace("/[^0-9.]/", '', $input);
回答by Veger
To satisfy my curiosity I asked about the speed of the proposed answers and as shown in preg_replace speed optimisation/it is (much) faster to use str_replace()than preg_replace().
为了满足我的好奇心,我询问了建议答案的速度,如preg_replace 速度优化中所示/它str_replace()比preg_replace().
So you might want to use str_replace()instead.
所以你可能想str_replace()改用。

