User787665
User787665

Reputation: 337

Insert space into string

Could anyone tell me how to insert a space in between characters in a string using PHP, depending on the length for a UK post code?

e.g. if the string is 5 charterers, insert a space after the second character? If it is 6 characters insert after the third etc?

Upvotes: 2

Views: 1514

Answers (1)

Lusitanian
Lusitanian

Reputation: 11122

Use regex: $formatted = preg_replace('/([a-Z0-9]{3})$/', ' \1', $postalCode);
Note that this only works on alphanumeric characters, but I'm assuming that's what the scope of the input should be.

Upvotes: 3

Related Questions