开发者

PHP Regular Expression to remove all characters other than digits and periods

开发者 https://www.devze.com 2022-12-17 19:06 出处:网络
I\'m trying to use preg_replace to remove all characters from a string except for numeric and period characters.

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 ch开发者_如何转开发aracter.

Can anyone help me out?


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


Remove everything that matches

[^0-9.]

e.g.

$output = preg_replace("/[^0-9.]/", "", $input);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号