PHP UK Postcode format function

/**
 * If postcode is 5 characters, insert space after the 2nd character
 * If postcode is 6 characters, insert space after the 3rd character
 * If postcode is 7 characters, insert space after the 4th character
 * @param $postcode
 * @return string
 */
function formatUKPostcode($postcode)
{
    $postcode = strtoupper(preg_replace("/[^A-Za-z0-9]/", '', $postcode));
 
    if(strlen($postcode) == 5) {
        $postcode = substr($postcode,0,2).' '.substr($postcode,2,3);
    }
    elseif(strlen($postcode) == 6) {
        $postcode = substr($postcode,0,3).' '.substr($postcode,3,3);
    }
    elseif(strlen($postcode) == 7) {
        $postcode = substr($postcode,0,4).' '.substr($postcode,4,3);
    }
 
    return $postcode;
}