Domanda

Ho bisogno di estrarre la prima parte del codice postale per il calcolo di ricerca utilizzando un database. Qualche idea?! Ho bisogno di questo per implementare un modulo di ricerca nel sito, che si affaccia per alcune informazioni rilevanti in base al codice postale. Ma la base di dati che sto avendo per codice postale, doesnt devono seconda parte del codice postale, solo la prima parte è lì. Il suo per codice postale Regno Unito. Quindi, tutte le idee?!

È stato utile?

Soluzione

Questo non coprirà il 100% di tutti i possibili codici postali del Regno Unito, ma farà per come 99,999% o giù di lì:)

/**
 * @param string $postcode UK Postcode
 * @return string
 */
function getUKPostcodeFirstPart($postcode)
{
    // validate input parameters
    $postcode = strtoupper($postcode);

    // UK mainland / Channel Islands (simplified version, since we do not require to validate it)
    if (preg_match('/^[A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?)\s*?\d[A-Z][A-Z]$/i', $postcode))
        return preg_replace('/^([A-Z]([A-Z]?\d(\d|[A-Z])?|\d[A-Z]?))\s*?(\d[A-Z][A-Z])$/i', '$1', $postcode);
    // British Forces
    if (preg_match('/^(BFPO)\s*?(\d{1,4})$/i', $postcode))
        return preg_replace('/^(BFPO)\s*?(\d{1,4})$/i', '$1', $postcode);
    // overseas territories
    if (preg_match('/^(ASCN|BBND|BIQQ|FIQQ|PCRN|SIQQ|STHL|TDCU|TKCA)\s*?(1ZZ)$/i', $postcode))
        return preg_replace('/^([A-Z]{4})\s*?(1ZZ)$/i', '$1', $postcode);

    // well ... even other form of postcode... return it as is
    return $postcode;
}

dati di test:

echo 'TW135BQ -> ', getUKPostcodeFirstPart('TW135BQ'), "\n";
echo 'gir0aa -> ', getUKPostcodeFirstPart('gir0aa'), "\n";
echo 'RG5 3SQ -> ', getUKPostcodeFirstPart('RG5 3SQ'), "\n";
echo 'AB51 0GQ -> ', getUKPostcodeFirstPart('AB51 0GQ'), "\n";
echo 'YO104EA -> ', getUKPostcodeFirstPart('YO104EA'), "\n";
echo 'SE154NS -> ', getUKPostcodeFirstPart('SE154NS'), "\n";
echo 'W1B4BD -> ', getUKPostcodeFirstPart('W1B4BD'), "\n";

Risultati:

TW135BQ -> TW13
gir0aa -> GIR0AA
RG5 3SQ -> RG5
AB51 0GQ -> AB51
YO104EA -> YO10
SE154NS -> SE15
W1B4BD -> W1B

Nota:. E 'vostra responsabilità di fornire Cap valida

EDIT: oops, non copre GIR 0AA, mi spiace

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top