jaxdevil Posted November 11, 2008 Share Posted November 11, 2008 I am trying to replace all of the text after the last '_' symbol in a string with the symbols [] , so if it says now some_line_1 or description_10 it will change to some_line_[] and description_[]. The code would need to read the string from left to right, finds the first '_' symbol, deletes everything after that symbol, and appends the symbols [] on the end. Any ideas how to do this? Thanks, SK Link to comment https://forums.phpfreaks.com/topic/132298-solved-replacing-text-of-a-string-afterthe-last-delimiter-in-the-string/ Share on other sites More sharing options...
premiso Posted November 11, 2008 Share Posted November 11, 2008 It would be a combination of substr and strrpos. You would use strpos to locate the last location of the last _ from there you would use substr to pull out 0 to that last position then append the [] to the end of the string. <?php $string = "index_ok_1"; $newString = substr($string, 0, strrpos($string, '_')) . "[]"; echo $newString; ?> Edit: Decided to add the code cause I was bored. Link to comment https://forums.phpfreaks.com/topic/132298-solved-replacing-text-of-a-string-afterthe-last-delimiter-in-the-string/#findComment-687826 Share on other sites More sharing options...
flyhoney Posted November 11, 2008 Share Posted November 11, 2008 This would also work I think: <?php $string = 'some_line_1'; echo preg_replace('/_([^_.*])$/i', '_[]', $string); ?> Link to comment https://forums.phpfreaks.com/topic/132298-solved-replacing-text-of-a-string-afterthe-last-delimiter-in-the-string/#findComment-687830 Share on other sites More sharing options...
premiso Posted November 11, 2008 Share Posted November 11, 2008 Another edit =\ Saw that you wanted to keep the last _ so here is a revised version <?php $string = "index_ok_1"; $newString = substr($string, 0, (strrpos($string, '_') + 1)) . "[]"; echo $newString; ?> Link to comment https://forums.phpfreaks.com/topic/132298-solved-replacing-text-of-a-string-afterthe-last-delimiter-in-the-string/#findComment-687831 Share on other sites More sharing options...
jaxdevil Posted November 11, 2008 Author Share Posted November 11, 2008 You did it perfect, it works like a charm! Thanks man! SK Link to comment https://forums.phpfreaks.com/topic/132298-solved-replacing-text-of-a-string-afterthe-last-delimiter-in-the-string/#findComment-687894 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.