[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 190
  • Last Modified:

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
0
mnb93
Asked:
mnb93
1 Solution
 
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now