如何正确添加和OR语句

时间:2014-08-18 12:18:02

标签: php regex

我正在尝试对序列号进行比较,如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 个答案:

答案 0 :(得分:3)

使用\d{3,4}$匹配最后的3位或4位数

这是完整的正则表达式

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

这是online demo

模式说明:

  ^                        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

答案 1 :(得分:3)

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

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

DEMO

<强>解释

  • ^断言我们刚开始。
  • ([0-9]{8}-)捕获8位数字和以下-符号。
  • ([0-9]{3,4})第二组捕获剩余的三位或四位数字。
  • $断言我们到底。

答案 2 :(得分:0)

您的代码运行正常,只需从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];
            }
    }
}
相关问题