0

I'm new to php and I'm trying to write a function to find an invalid postcode. This is an option, however I've been told this isnt the ideal format:

function postcode_valid($postcode) {
    return preg_match('/\w{2,3} \d\w{2}/', $postcode);
}

//more accurate
//[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}

I understand the first function, but I don't know how to write the 'ideal' solution as a function, please can you advise?

  • 1
    You need to provide examples of valid post codes. What does valid mean for you? Is that comment "more accurate" the regex you want to use in PHP instead of the one you used a few lines above? – ssc-hrep3 Feb 12 '17 at 14:35
  • There are a lot of postcode types for each country you live in. As ssc-hrep3 said, provide us a list of postcodes that should, and shouldn't match. – Mateus Feb 12 '17 at 14:37
  • Thanks all , I was referring to UK postcodes. I've now got the answer from ssc-hrep3, thanks for your help. – Vicki Marshall Feb 12 '17 at 15:54
  • I don't think your original attempt even matches my postcode. – Joe C Feb 12 '17 at 19:40
  • As i said i'm new to this, so I won't be perfect first time. – Vicki Marshall Feb 13 '17 at 23:02

1 Answers1

0

If the regular expression you provided in the comment field is the correct one and you don't know how to use it in PHP, here is the solution:

function postcode_valid($postcode) {
   return preg_match('/^[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}$/', $postcode);
}

You need to add two slashes (one in front, one at the end) of the regular expression and pack it in a string in PHP. I would also highly recommend you to use ^ and $ at the beginning resp. at the end of the regular expression to indicate the beginning and the end of the string (otherwise, it is valid, if only a part of the string contains the correct pattern i.e. a longer string with a valid part would be accepted.) Here is a live example.


If you are looking for the validation of a UK post code, you should be using the following regex instead (source):

(GIR 0AA)|((([A-Z-[QVX]][0-9][0-9]?)|(([A-Z-[QVX]][A-Z-[IJZ]][0-9][0-9]?)|(([A-Z-[QVX]][0-9][A-HJKPSTUW])|([A-Z-[QVX]][A-Z-[IJZ]][0-9][ABEHMNPRVWXY])))) [0-9][A-Z-[CIKMOV]]{2})

If you are looking for something else, please provide a comment below.

Community
  • 1
  • 1
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87