0

My questions sound may different but I am really looking for solution.

I have a variable in PHP, let's say $check, containing a string. It can be either an address or a postal code. Is there any rule we can apply here to check whether variable has postcode or address?

Edit: This website is for UK

Thanks

Tchoupi
  • 14,560
  • 5
  • 37
  • 71
Shail
  • 1,565
  • 11
  • 24

2 Answers2

7

Quite detailed link: here

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;
    }

Use:

$e = "AB235RB";
if (IsPostcode($e))
print "Valid Post Code";
else
print "Invalid Post Code";

I have written a UK postcode validator based off this, so I know it works :)

Chris
  • 5,516
  • 1
  • 26
  • 30
  • You will also want to deal with spaces as most people format their postcode as "bh20 6dq" for instance – Chris Sep 25 '12 at 15:53
  • (Incorrect comment deleted, and +1 added for spotting those annoying London postcodes) – andrewsi Sep 25 '12 at 15:59
0

New Answer

As Marc B pointed out, my initial answer will not work due to the alphanumeric quality of UK zipcodes. In that case, I suggest preg_match to regex match the zipcode, or you could do a strlen on $check and look for the length of a zip code if you can be sure no addresses will ever be that length.

I'd recommend reading this question for a good discussion on the regex required.

Old Answer

If it is a simple zip code (i.e. not like 12345-1234), you could check with is_numeric. That is a bit of a hack, but it may suit your purposes. Even if it is a complex zip, you could always use str_replace to remove the - and check is_numeric. This is of course assuming the address has some character/string contents and is not fully numeric.

Community
  • 1
  • 1
Eric H
  • 1,100
  • 16
  • 32