PHP - Convert ereg to preg_match
I have a script I have used for quite a while that validates UK postcodes, issue I have is one part of the function uses ereg
rather than preg_match
.
Could someone point me in the right direction with the below please? I have added delimiters but not getting the same results as I was before.
$alpha1 = "[abcdefghijklmnoprstuwyz]";
$alpha2 = "[abcdefghklmnopqrstuvwxy]";
$alpha3 = "[abcdefghjkstuw]";
$alpha4 = "[abehmnprvwxy]";
$alpha5 = "[abdefghjlnpqrstuwxyz]";
// Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
$pcexp[0] 开发者_JAVA技巧= '/^(' . $alpha1 . '{1}' . $alpha2 . '{0,1}[0-9]{1,2})([0-9]{1}' . $alpha5 . '{2})$/';
// Expression for postcodes: ANA NAA
$pcexp[1] = '/^(' . $alpha1 . '{1}[0-9]{1}' . $alpha3 . '{1})([0-9]{1}' . $alpha5 . '{2})$/';
// Expression for postcodes: AANA NAA
$pcexp[2] = '/^(' . $alpha1 . '{1}' . $alpha2 . '[0-9]{1}' . $alpha4 . ')([0-9]{1}' . $alpha5 . '{2})$/';
// Exception for the special postcode GIR 0AA
$pcexp[3] = '/^(gir)(0aa)$/';
// Standard BFPO numbers
$pcexp[4] = '/^(bfpo)([0-9]{1,4})$/';
// c/o BFPO numbers
$pcexp[5] = '/^(bfpo)(c\/o[0-9]{1,3})$/';
At a first glance, everything looks OK, but you need to make the regex case-insensitive by adding an i
after the closing delimiter:
$pcexp[4] = '/^(bfpo)([0-9]{1,4})$/i';
and so on.
Your regexes don't allow for spaces between the parts of the postcode. Is this intentional? If not, add a \s*
everywhere spaces are legal
Also, you can drop all instances of {1}
and replace each {0,1}
with ?
.
精彩评论