This is my string:
Hello world Hello How are You Hello world
I want to replace last Hello world
to HW
Result:
Hello world Hello How are You HW
str_replace
replaces all Hello world
but I want to replace from end (if exists)
CodePudding user response:
I guess you want to use a single function for this, but it doesn't exist. You can build your own function, like this:
<?php
function str_replace_last($search, $replace, $subject)
{
$pos = strrpos($search,$replace);
if ($pos === FALSE) return search;
return substr($search, 0, $pos) . $subject .
substr($search, $pos strlen($replace));
}
echo str_replace_last('Hello world Hello How are You Hello world',
'Hello world', 'HW');
This returns:
Hello world Hello How are You HW
See: strrpos()
Note that this function doesn't work with array arguments as the original str_replace()
does.
CodePudding user response:
If you want you can use preg_replace()
using the pattern Hello world$
<?php
$re = '/Hello world$/m';
$str = 'Hello world Hello How are You Hello world';
echo preg_replace($re, 'HW', $str);
?>
This would need the least code if do it in one line
preg_replace('/Hello world$/m','HW','Hello world Hello How are You Hello world');