RockDance
RockDance

Reputation: 91

How To use preg_match for - , + , . values?

I use this preg_match condition for matching positive, negative and decimal values

/^[0-9,-\.]{1,50}$/

But when I enter --34.000 it does not show error, when I enter 34...9868 it does not show error, what I want is that it must accept only positive, negative and decimal values.

Upvotes: 1

Views: 1899

Answers (4)

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

As yes123 stated, there are better ways to detect if a given input string is a numeric value. If you'd like to stick to regular expressions, the following might be OK for you:

/^-?[0-9]+(?:\.[0-9]+)?$/

Explanation:

  • match start of the string ( ^)
  • match a possible - character (-?); the ? means "not required"
  • match at least one number ([0-9]+)
  • possibly match the whole statement in the parentheses ((?:...)?); ?: means "do not capture the subpattern"
    • a point (\.); the . needs to be escaped due to its special function
    • at least one number ([0-9]+)
  • match end of the string ($)

Upvotes: 4

Jon Benedicto
Jon Benedicto

Reputation: 10582

You need to split up your regular expression so that it only accepts the characters in the right places. For example:

/^[+\-]?([0-9]+,)*[0-9]+(\.[0-9]+)?$/

To explain this expression:

[+\-]?: This checks for a + or - prefix to the number. It's completely optional, but can only be a + or -.

([0-9]+,)*: This allows an optional set of comma-delimited numbers. This is for the thousands, millions etc.

[0-9]+: This requires that the value contains at least some numbers

(\.[0-9]+)?: Finally, this allows an optional decimal point with trailing numbers.

Upvotes: 2

venimus
venimus

Reputation: 6047

try this regex ^-?\d*\.?\d+$ i suppose it however cannot be limited to 50 chars

Upvotes: 0

dynamic
dynamic

Reputation: 48091

Better if you use something like is_numeric() if yuo need to check if it's a number.

And your regex is totally broke because as now it can accept even only a string containing 50 dots

Upvotes: 4

Related Questions