doudu5029 2013-09-20 05:00
浏览 27
已采纳

PHP表单。 需要检查第一个字母[关闭]

In a form I have an ID field, which needs to check that the first letter is "P" and is 5 characters long.

I have looked into preg_match but I have no idea how to get it working. It seems to be able to check how many "P"s the would be and where they are, but how do I get that to check that only entries starting with "P" are passed.

Big time PHP noobie so doesn't need to be anything awesome. I really don't get PHP. :(

  • 写回答

7条回答 默认 最新

  • doumu9019 2013-09-20 05:09
    关注

    To check if a string starts with P and is 5 characters long, using preg_match, as you asked for, I would write (lazily)

    <?php
      if (preg_match('/^P....$/', $your_ID_variable) === 1) {
        print 'your ID is starting with a P and is 5 characters long.';
      }
    ?>
    

    But as posted from others, there are other ways to do it, like:

    <?php
       if ((strlen($your_ID_variable) == 5)
       && (strpos($your_ID_variable, 'P') === 0)) {
        print 'your ID is starting with a P and is 5 characters long.';
       }
    ?>
    

    Here are some sources you could have found:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?