Jump to content

[SOLVED] Replacing text of a string afterthe last delimiter in the string


jaxdevil

Recommended Posts

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

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.

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;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.