Reputation: 1151
I am trying to do a comparison of serial numbers like so 20140831-123 or 20140831-1234 so the form can accept our new serial numbers which contain 4 last numbers. So far I have tried an elseif statement and an or operator with no results what am I doing wrong? is there a way to change the reg expression itself to accept 3 or 4 digits at the end of the serial?
if($name == 'newserial1'){
$newserial1 = $_POST['newserial1'];
if($newserial1 != '') {
if(!preg_match('/^([0-9]{8}-)([0-9]{3})$/', $newserial1) ||
(!preg_match('/^([0-9]{8}-)([0-9]{4})$/', $newserial1))) {
$result['valid'] = false;
$result['reason'][$name] = 'Incorrect Serial Number.';
}
}
}
Upvotes: 0
Views: 52
Reputation: 46861
Use \d{3,4}$
to match 3 or 4 digit in the end
Here is the complete regex pattern
^(\d{8})-(\d{3,4})$
Here is online demo
Pattern explanation:
^ the beginning of the string
( group and capture to \1:
\d{8} digits (0-9) (8 times)
) end of \1
- '-'
( group and capture to \2:
\d{3,4} digits (0-9) (between 3 and 4 times)
) end of \2
$ the end of the string
Upvotes: 3
Reputation: 1334
Your code works fine, just remove Not
operator from your if clauses, and add matches to preg_match:
if($name == 'newserial1'){
$newserial1 = $_POST['newserial1'];
if($newserial1 != '') {
if(preg_match('/^([0-9]{8}-)([0-9]{3})$/', $newserial1, $matches) ||
(preg_match('/^([0-9]{8}-)([0-9]{4})$/', $newserial1, $matches))) {
//$result['valid'] = false;
//$result['reason'][$name] = 'Incorrect Serial Number.';
$result['matches'] = $matches[2];
}
}
}
Upvotes: 0
Reputation: 174796
Just use the below regex to match last 3 or 4 digits also,
^([0-9]{8}-)([0-9]{3,4})$
Explanation:
^
Asserts that we are at the start.([0-9]{8}-)
Captures 8 digits and a following -
symbol.([0-9]{3,4})
Remaining three or four digits are captured by the second group.$
Asserts that we are at the end.Upvotes: 3