Jump to content

Validate numbers


Nodral

Recommended Posts

Hi All

 

I'm a bit of a newbie to regex and am struggling with what seems like the most basic preg_replace.

 

I need to validate numbers and remove anything non-numeric from a string.

 

ie 4.5volts would become 4.5

-67 degrees would be -67

 

I have this

 

preg_replace('/[^.-0-9]/', '', $aValue['value']);

 

however there can only be one minus and it must be at the start, and there can only be one decimal point.

 

Any help is much appreciated.

Link to comment
https://forums.phpfreaks.com/topic/268285-validate-numbers/
Share on other sites

You really should be using typecasting for this, as mentioned above.

 

That said, the problems you had with your second RegExp are as follows:

  1. [*]Missing delimiters, which causes the RegExp engine to assume that the opening [ is a delimiter. Thus the error.

[*]Use of word boundaries. Especially in between the notation sign and the value.

You don't need the word boundaries at all, as the + is a greedy modifier and you've asked it to match digits only. Also, you could have used \\d instead of [0-9] to tell the RegExp engine that you wanted a digit.

Link to comment
https://forums.phpfreaks.com/topic/268285-validate-numbers/#findComment-1377343
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.