tags:

views:

29

answers:

2

Hi, I'm trying to use preg_replace to remove all characters from a string except for numeric and period characters.

I can remove everything but numbers, however how can I make an exception for the '.' period character.

Can anyone help me out?

Thanks.

+2  A: 

Remove everything that matches

[^0-9.]

e.g.

$output = preg_replace("/[^0-9.]/", "", $input);
Tomalak
+3  A: 

Try this:

$clean = preg_replace('/[^\\d.]+/', '', $str);

But you could also use [^0-9.] if you’re more familiar with that. Note that the . doesn’t need to be escaped inside the character class declaration as it’s not a special character inside there (only ], \ and depending on the context also ^ and -).

Gumbo
not `+`, but rather `g` :)
Tomalak
@Tomalak: There is no *g* modifier in PHP’s PCRE. Replacing is always global.
Gumbo
@Gumbo: Thanks for clarifying, I wasn't aware of that.
Tomalak