supanoob Posted February 11, 2016 Share Posted February 11, 2016 So i have a database with a list of Towns and their relevant postcode letters (DN = Doncaster, S = Sheffield etc) i want to be able to find out what town they're from, using the postcode they have submitted, but i'm unsure on how to break away the characters before the first number in the postcode..... so for example someone submits DN2 6PJ how to do break away the DN so i can return Doncaster or the same if it was S1 4QJ how would i break away the S to return sheffield? Quote Link to comment https://forums.phpfreaks.com/topic/300788-postcode-check/ Share on other sites More sharing options...
Jacques1 Posted February 11, 2016 Share Posted February 11, 2016 Use a regular expression to simultanously validate the input and extract the postcode area: <?php // test input $postcode = 'S1 4QJ'; $postcode_regex = '/\\A(?P<postcode_area>[A-Z][A-Z]?)\\d[A-Z\\d]? \\d[A-Z]{2}\\z/'; if (preg_match($postcode_regex, $postcode, $postcode_matches)) { var_dump($postcode_matches['postcode_area']); } else { echo 'Incorrect postcode.'; } Quote Link to comment https://forums.phpfreaks.com/topic/300788-postcode-check/#findComment-1531014 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.