使用preg_match验证字符串格式
I have an html form with an input for a sales order number which should have the format of K1234/5678. It should always start with the letter K then 4 numbers, a / and followed by another set of 4 numbers.
I'm trying to validate the formatting using preg_match and I'm getting lost in the syntax of preg_match. From http://php.net/manual/en/function.preg-match.php I've gotten close. With the following code I'm able to verify that it contains at least 1 letter, some numbers and at least 1 non- alphanumeric value.
$so= $_POST['so'];
if (preg_match(""/^(?=.*[a-z]{1})(?=.*[0-9]{4})(?=.*[^a-z0-9]{1})/i", $so))
{
print $so;
}
What is the correct syntax to use for this? Is preg_match even the best way to do this?
我有一个html表单,其中包含一个销售订单号的输入,其格式应为K1234 / 5678。 它应始终以字母K开头,然后是4个数字,a /后跟另一组4个数字。 p>
我正在尝试使用preg_match验证格式,我在preg_match的语法中迷路了。 来自 http://php.net/manual/en/function.preg-match。 php 我已经接近了。 使用以下代码,我能够验证它包含至少1个字母,一些数字和至少1个非字母数字值。 p>
$ so = $ _POST ['so'];
if(preg_match(“”/ ^(?=。* [az] {1})(?=。 * [0-9] {4})(?=。* [^ a-z0-9] {1})/ i“,$ so))
{
print $ so;
}
pre>
用于此的正确语法是什么?preg_match甚至是最好的方法吗? p>
div>
Try this:
preg_match("#^K[0-9]{4}/[0-9]{4}$#i", $so)
Explanation:
The #
characters are regular expression delimiters - they indicate the start/end of the pattern. The ^
and $
indicate the start and end of the string - this means that it will only match if your sales order number is the only thing in the string. The letter K
means match that letter, [0-9]{4}
means match a digit exactly 4 times. The i
at the end means a case-insensitive match - the K
will match either "K" or "k".
When developing regular expressions, I often use regular expression testers - these allow you to enter your data and try a bunch of different things to refine your regex. Google PHP regex tester to find a list of tools. Also, there's a very complete reference to regular expressions at http://www.regular-expressions.info/.