0

I'm using this validator:

//validate postcode
function IsPostcode($postcode)
{
    $postcode = strtoupper(str_replace(' ','',$postcode));
    if(preg_match("/^[A-Z]{1,2}[0-9]{2,3}[A-Z]{2}$/",$postcode) || preg_match("/^[A-Z]{1,2}[0-9]{1}[A-Z]{1}[0-9]{1}[A-Z]{2}$/",$postcode) || preg_match("/^GIR0[A-Z]{2}$/",$postcode))
    {
        return true;
    }
    else
    {
        return false;
    }
}

From this link.

But I want to be able to validate postcodes like ME20 and TN10 instead of a full blown ME20 4RN, TN0 4RN. This is the part of the postcode known as the 'outward code'.

Can someone help me out with the regex?

AdamJones
  • 652
  • 1
  • 15
  • 38
Adam
  • 1,957
  • 3
  • 27
  • 56
  • http://regular-expressions.info/tutorial.html – deceze Jul 31 '13 at 09:45
  • There is a library available to do this https://gist.github.com/ChrisMcKee/4452116 just set the incode optional to only validate the first part – Anigel Jul 31 '13 at 09:45
  • How much do you understand about regex patterns? It would only take the most basic regex knowledge to work out your answer from the starting point you've already got. I suggest going and [reading up a bit more about regex](http://www.regular-expressions.info/) rather than asking such a basic question. You'll learn a lot more that way. – Spudley Jul 31 '13 at 09:47
  • I know nothing about them really, but I did just buy "Mastering Regular Expressions" – Adam Jul 31 '13 at 09:50

1 Answers1

2

you can use my updated regex to solve you problem

it working from my end to validate UK zip code

<?php 
function IsPostcode($postcode)
{
    $postcode = strtoupper(str_replace(' ','',$postcode));
    if(preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]?[\s]?[0-9][ABD-HJLNP-UW-Z]{2}$)/i",$postcode) || preg_match("/(^[A-Z]{1,2}[0-9R][0-9A-Z]$)/i",$postcode))
    {    
        return true;
    }
    else
    {
        return false;
    }
}

echo $result = IsPostcode('ME20');
?>

OUTPUT

1

Hope this will sure help you.

liyakat
  • 11,825
  • 2
  • 40
  • 46
  • This doesn't seem to work for some codes. The very first one I checked it with, NW1 doesn't make a match. – AdamJones Aug 11 '21 at 10:57