skip to Main Content

The UK post code is like this BB9 7RL

I would like to keep the first block then the first letter of the second block like this BB9 7

I am using this at the moment but it only gives me the first block like this BB9

preg_split('/[, ();.]/', trim($string))[0]

2

Answers


  1. If you know the format of the string upfront, you can split and check if there are at least 2 parts.

    Then concat the first character from the second item in the array.

    For the pattern you can add a multiplier + for matching 1 or more times, in case you have consecutive characters that are matched by what is listed in the character class, which would give you empty items in the resulting array of preg_split.

    $string = "BB9 7RL";
    $result = preg_split('/[, ();.]+/', trim($string));
    $postalCode = $result[0];
    
    if (count($result) > 1) {
        $postalCode .= $result[1][0];
    }
    echo $postalCode;
    

    Output

    BB97
    

    If you first want to validate the string for the postalcode first, you can refer to this page RegEx for matching UK Postcodes

    Login or Signup to reply.
  2. You can try this code specifically for your case:

    $postcode = "BB9 7RL";
    $pattern = '/^([A-Z]{1,2}[0-9][A-Z0-9]?)s*([0-9])[A-Z]{2}$/i';
    
    if (preg_match($pattern, $postcode, $matches)) {
        $formatted = $matches[1] . ' ' . $matches[2];
        echo $formatted; // Outputs: BB9 7
    } else {
        echo "Invalid postcode";
    }
    

    you can check how it works here

    or here is the UK recommended postcode regexp example

    $postcode = "BB9 7RL";
    $pattern = '/([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))s?[0-9][A-Za-z]{2})/';
    
    if (preg_match($pattern, $postcode, $matches)) {
        $formatted = substr($matches[0], 0, strpos($matches[0], ' ')) . ' ' . $matches[0][strpos($matches[0], ' ') + 1];
        echo $formatted; // Outputs: BB9 7
    } else {
        echo "Invalid postcode";
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search