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
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.Output
If you first want to validate the string for the postalcode first, you can refer to this page RegEx for matching UK Postcodes
You can try this code specifically for your case:
you can check how it works here
or here is the UK recommended postcode regexp example