Reputation: 150
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
Reputation: 786289
Using lookahead regex search for:
_5(?=})
And replace by:
_DT5
Here (?=})
will make sure that to _5
followed by }
.
Upvotes: 0
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