I have a number of restaurants who all deliver to certain postcode areas in London, for example:
EC1WC1WC2<
The below graphic explains the format of UK postcodes:
Source: https://www.getthedata.com/postcode (My site) So you can see that you need Outcode which given your requirement (given a full postcode with no space) is simply your space-free postcode minus the last three characters.
In PHP this would be:
$outcode = substr($postcode_no_space, 0, -3)
Of course this does not help with validating the postcode, but as you point out in your comments the question is not about validation.