1

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] = '/^(' . $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})$/';
lethalMango
  • 4,433
  • 13
  • 54
  • 92
  • possible duplicate of [Converting ereg expressions to preg](http://stackoverflow.com/questions/6270004/converting-ereg-expressions-to-preg) – netcoder Jun 09 '11 at 16:01
  • This was for this specific code rather than in general. I had tried to fix it myself which seems to have worked with a bit of input from Tim Pietzcker – lethalMango Jun 09 '11 at 16:17

1 Answers1

1

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 ?.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Hi Tim, thanks for that. Spaces are removed from the string prior to checking. Could you tell me what what happens when changing `{0,1}` to `?` and dropping `{1}`? – lethalMango Jun 09 '11 at 16:05
  • Nothing changes. `?` means zero or one, and `{1}` is simply redundant. – Tim Pietzcker Jun 09 '11 at 16:19