如何正确地添加或语句


How to add and OR statement correctly

我正试图对序列号进行比较,如20140831-123或20140831-1234,以便表单可以接受包含4个最后数字的新序列号。到目前为止,我已经尝试了一个elseif语句和一个或操作符没有结果我做错了什么?是否有一种方法来改变reg表达式本身接受3或4位数字在串行结束?

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.';
            }
        }
    }

只需使用下面的正则表达式匹配最后3或4位数字,

^([0-9]{8}-)([0-9]{3,4})$

演示

解释:

  • ^断言我们处于开始。
  • ([0-9]{8}-)捕获8位数字和后面的-符号。
  • ([0-9]{3,4})剩余的三位或四位数字由第二组捕获。
  • $断言我们已经到了终点。

使用'd{3,4}$匹配末尾的3或4位数字

下面是完整的正则表达式模式

^('d{8})-('d{3,4})$

这是在线演示

模式说明:

  ^                        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

您的代码工作得很好,只需从您的if子句中删除Not操作符,并将匹配添加到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];
            }
    }
}