Right, got your point - but is this user input?
Originally Posted by pacman2504
If so then only collect what you want in the first place, as I suggested.
If not, so its coming from another system - well can you be sure it is a correctly formed and legal postcode?
If so then its going to be pretty easy:
Thats one way of doing it IF you can trust that you are being given a legal postcode.
$pc= "CH13 2AA";
$pc_bits = split(' ' , $pc );
$pc_postfix = $pc_bits ;
echo 'Prefix = ' . substr( $pc, 0, 2 );
echo 'PCArea = ' . (int)substr( $pc, 2, 2 );
// you dont want the last letters, and it starts with a number so turn into an int
echo 'Postfix = ' . (int)$pc_postfix ;
Another way is to use a regular expression - if you google for UK Postcode regex then you will find several good ones.
That regex has to be used inside functions like preg_match, preg_match_all etc.
I dont know if this is your case but without doubt the best way to go from a security and reliablity POV, is to only allow users to enter letters and numbers in a manner that makes it easy for you to check.
e.g. none of the above will work for typical errors ppl make, like this:
CH132AA ( no space )
CH13-2AA (dash not space )
CH17 0AA ( illegal pattern )
CH1OAA (letter O not a zero)