JustinK101 Posted May 13, 2010 Share Posted May 13, 2010 What is the best way to do the following string manipulation. $string = "012354631556" I want to add brackets after the last character, and then before the 6th to last character. So: $string = "012354[631556]" What is the best way to do this? Thanks. Link to comment https://forums.phpfreaks.com/topic/201685-manipulate-string-insert-characters/ Share on other sites More sharing options...
kenrbnsn Posted May 13, 2010 Share Posted May 13, 2010 One way would be to use the substr function: <?php $string = '012354631556'; $rem_len = (strlen($string) - 6) * -1; $new_str = substr($string,0,6) . '[' . substr($string,$rem_len) . ']'; echo $new_str; ?> Ken Link to comment https://forums.phpfreaks.com/topic/201685-manipulate-string-insert-characters/#findComment-1058012 Share on other sites More sharing options...
JustinK101 Posted May 13, 2010 Author Share Posted May 13, 2010 Ken, Thanks for the code, but that code assumes the string is always fixed length, it is not. For example it needs to work with: $string = "24743734" Into $string = "24[743734]" Link to comment https://forums.phpfreaks.com/topic/201685-manipulate-string-insert-characters/#findComment-1058019 Share on other sites More sharing options...
litebearer Posted May 13, 2010 Share Posted May 13, 2010 Perhaps... $string = "0123456789876543210"; $new_string = substr($string, 0, -6) . "[" . substr($string, -6) . "]"; Link to comment https://forums.phpfreaks.com/topic/201685-manipulate-string-insert-characters/#findComment-1058021 Share on other sites More sharing options...
kenrbnsn Posted May 13, 2010 Share Posted May 13, 2010 Sorry, I mis-read the requirements. Ken Link to comment https://forums.phpfreaks.com/topic/201685-manipulate-string-insert-characters/#findComment-1058024 Share on other sites More sharing options...
litebearer Posted May 13, 2010 Share Posted May 13, 2010 you should check that the length of the string is atleast 7 characters or it might throw an error Link to comment https://forums.phpfreaks.com/topic/201685-manipulate-string-insert-characters/#findComment-1058025 Share on other sites More sharing options...
litebearer Posted May 13, 2010 Share Posted May 13, 2010 example using various lengths... http://nstoia.com/bracket.php Link to comment https://forums.phpfreaks.com/topic/201685-manipulate-string-insert-characters/#findComment-1058031 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.