PHP- Postcode format function

This PHP function formats a string (as long as it is between 5-7 charcters in length after removing spaces) into a proper postcode format. So for example, the following postcode "CM189Th" will be returned as "CM18 9TH"

If the string being passed is not a valid length, formatting is bypassed and the original string is returned.

The function will return the following formats:

  • LN NLL
  • LLN NLL
  • LNN NLL
  • LLNN NLL
  • LLNL NLL
  • LNL NLL

Postcode Format Function 1 (only formats valid postcodes)

If the UK postcode you're trying to format is ALWAYS going to be valid, then use the following code. If not, I would recommend using the second example.

			//format postcode
			function postcodeFormat($postcode)
			{
				//remove non alphanumeric characters
				$cleanPostcode = preg_replace("/[^A-Za-z0-9]/", '', $postcode);

				//make uppercase
				$cleanPostcode = strtoupper($cleanPostcode);

				//insert space
				$postcode = substr($cleanPostcode, 0, -3) . " " . substr($cleanPostcode, -3);

				return $postcode;
			}
			

Postcode Format Function 2 (formats invalid postcodes)

			//format postcode
			function postcodeFormat($postcode)
			{
				//trim and remove spaces
				$cleanPostcode = preg_replace("/[^A-Za-z0-9]/", '', $postcode);

				//make uppercase
				$cleanPostcode = strtoupper($cleanPostcode);

				//if 5 charcters, insert space after the 2nd character
				if(strlen($cleanPostcode) == 5)
				{
					$postcode = substr($cleanPostcode,0,2) . " " . substr($cleanPostcode,2,3);
				}

				//if 6 charcters, insert space after the 3rd character
				elseif(strlen($cleanPostcode) == 6)
				{
					$postcode = substr($cleanPostcode,0,3) . " " . substr($cleanPostcode,3,3);
				}


				//if 7 charcters, insert space after the 4th character
				elseif(strlen($cleanPostcode) == 7)
				{
					$postcode = substr($cleanPostcode,0,4) . " " . substr($cleanPostcode,4,3);
				}

				return $postcode;
			}
			

Useage (for both examples)

			//echo formatted postcode
			$postcode = "cm284hy";

			echo postcodeFormat($postcode);
			//returns CM28 4HY