RegExp

Possible inputs:

{d}= digit(s)

{d}.{d}.{d}.{d} AND {d}.{d}.{d}

Now how can I validate that $x is valid?

BTW {d} could equal 23746983268345687346 or 3, but not -658

Steven
LVL 5
mnb93Asked:
Who is Participating?
 
m1tk4Commented:
preg_match('/^\d+\.\d+\.\d+(\d+\.)?$/', $x)
0
 
neesterCommented:
if (preg_match("/[0-9+]/",$x) {
  //VALID
}else{
  //INVALID
}
0
 
neesterCommented:
Sorry,

 if (preg_match("/^[0-9]+$/",$x) {
  //VALID
}else{
  //INVALID
}


[0-9]+
means any numbers between 0 and 9.
The + means there must be atleast 1 or more.
and the ^ and $ mean it must span the whole block.
(^=start, $=end)
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
mnb93Author Commented:
m1tk4's way looks correct, however neester's way doesn't look correct to me, how would: /^[0-9]+$/",$x parse true this: 2.3.4.5?

Thanks.
0
 
tolgaongCommented:
$number="658";

if (preg_match('/^\\d+$/', $number)) echo "VALID";
else echo "NOT VALID";
0
 
neesterCommented:
Awww sorry!

I read this wrong:

"BTW {d} could equal 23746983268345687346 or 3, but not -658"


This will work :)

if (preg_match("/^([0-9]|\.)+$/",$x) {
  //VALID
}else{
  //INVALID
}
0
 
tdterryCommented:
How about this:

if (preg_match("/^[\d\.]+$/", $x) {
  // $x is only digits and dots
  $digits = explode('.', $s);
  // now you can use $digits[0], [1], [2], etc to get the blocks of digits (see warning below)
} else {
  // not match
}

This is similar to neester's proposed solution but goes a step further to separate the digits.  Warning: Both my and neester's comments have a similar "issue" that they accept {d}..{d} with multiple period separators.  If single periods are a must and ONLY three or four blocks of digits are allowed, m1k4 was ALMOST correct.  His last grouping had the period and \d reversed.   Should be:

preg_match("/^\d+\.\d+\.\d+(\.\d+)?$/", $x);
0
 
m1tk4Commented:
preg_match("/^[\d\.]+$/", $x)  will also match ...3.2.


preg_match("/^\d+\.\d+\.\d+(\.\d+)?$/", $x); is a correct answer
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.