Manu
Manu

Reputation: 150

Replace the characters after the last underscore

I have a string with the following structure. I want to replace the character(s) after the last underscore.

$string = ' 
   {$9018049_text_50024080_3} : {$9018049_text_53441884_3} 
   {$9018049_text_50024080_4} : {$9018049_text_53441884_4} 
   {$9018049_text_50024080_5} : {$9018049_text_53441884_5} 
  ';

For example, If I replace the character "5" with "DT5", the output should be

$string = ' 
   {$9018049_text_50024080_3} : {$9018049_text_53441884_3} 
   {$9018049_text_50024080_4} : {$9018049_text_53441884_4} 
   {$9018049_text_50024080_DT5} : {$9018049_text_53441884_DT5} 
  ';

I have tried with str_replace, but the output is

$string = ' 
   {$9018049_text_DT50024080_3} : {$9018049_text_DT53441884_3} 
   {$9018049_text_DT50024080_4} : {$9018049_text_DT53441884_4} 
   {$9018049_text_DT50024080_DT5} : {$9018049_text_DT53441884_DT5} 
  ';

This is not what I want. Any help will be appreciated.

Upvotes: 0

Views: 490

Answers (3)

user905476
user905476

Reputation:

select last line:

\n.*$

replace regex:

_\d(?=})

Upvotes: 0

anubhava
anubhava

Reputation: 786289

Using lookahead regex search for:

_5(?=})

And replace by:

_DT5

Here (?=}) will make sure that to _5 followed by }.

RegEx Demo

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

If I understand well:

$string = str_replace('_5}', '_DT5}', $string);

if you want to do the same for each content between curly brackets whatever the number:

$string = preg_replace('~_(\d+})~', '_DT$1', $string);

Upvotes: 3

Related Questions