tags:

views:

106

answers:

4

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)

Any ideas how to do this? Is there a function prebuilt?

thanks

+1  A: 
preg_replace('/[^0-9.]/', '', $string);
Ionuț G. Stan
Escape the dot.
Robin
Robin, there's no need. I've tested it before posting and works OK.
Ionuț G. Stan
@Robin, you would need to escape the period if it were outside of the brackets []. inside the square brackets the period is not treated as a special character
Jonathan Fingland
@Robin: The text inside the [] is defining a set of characters; it doesn't really make much sense for the '.' character to mean any character in that context.
CodeSavvyGeek
+9  A: 
$str = preg_replace('/[^0-9.]+/', '', $str);

replace substrings that do not consist of digits or . with nothing.

Don
Someone who took the time to (briefly) comment on his answer!
Veger
@Veger, SO tends to promote typos and short answers -- well I try to fight it.
Don
@Don: Good that makes at least two of us!
Veger
A: 
$input = 'some str1ng 234'
$newString = preg_replace("/[^0-9.]/", '', $input)
Juraj Blahunka
A: 

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().

So you might want to use str_replace() instead.

Veger
But you can't really use `str_replace()` in this case, unless you want to hardcode all characters which are not numbers.
kemp
@kemp, hm... yes that's true. That would be too much :)
Veger