AdRock Posted March 19, 2008 Share Posted March 19, 2008 I have a string and I want to split it into 2 parts but the last part has to be 3 characters. What it is, is a uk postcode which is in the database like CF127HG and i want to format the output like CF12 7HG How do i do that? Link to comment https://forums.phpfreaks.com/topic/96999-how-to-split-a-string-so-the-last-part-of-string-is-3-letters/ Share on other sites More sharing options...
Jeremysr Posted March 19, 2008 Share Posted March 19, 2008 substr() could do it: $first_part = substr($postcode, 0, strlen($postcode)-3); $second_part = substr($postcode, strlen($postcode)-4); Link to comment https://forums.phpfreaks.com/topic/96999-how-to-split-a-string-so-the-last-part-of-string-is-3-letters/#findComment-496365 Share on other sites More sharing options...
AdRock Posted March 19, 2008 Author Share Posted March 19, 2008 Thinking about it, the word doesn't have to be split but a space added to the string before the last 3 characters Link to comment https://forums.phpfreaks.com/topic/96999-how-to-split-a-string-so-the-last-part-of-string-is-3-letters/#findComment-496368 Share on other sites More sharing options...
Jeremysr Posted March 19, 2008 Share Posted March 19, 2008 You'd still use the substr()'s but concatenate them together with a space in between: $postcode = substr($postcode, 0, strlen($postcode)-3) . ' ' . substr($postcode, strlen($postcode)-4); Link to comment https://forums.phpfreaks.com/topic/96999-how-to-split-a-string-so-the-last-part-of-string-is-3-letters/#findComment-496372 Share on other sites More sharing options...
AdRock Posted March 19, 2008 Author Share Posted March 19, 2008 thanks jeremy, worked a treat. just had to change them both to -3 to allow for smaller postcodes Link to comment https://forums.phpfreaks.com/topic/96999-how-to-split-a-string-so-the-last-part-of-string-is-3-letters/#findComment-496377 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.