Anyone know of a very fast way to replace the last occurrence of a string with another string in a string?
+5
A:
You can use this function:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos === false)
{
return $subject;
}
else
{
return substr_replace($subject, $replace, $pos, strlen($search));
}
}
captaintokyo
2010-10-01 00:00:10
For safeties sake I'd add a check that `strrpos` doesn't return false, but otherwise OK.
Wrikken
2010-10-01 00:38:36
Yeah, you are right. I will update my answer.
captaintokyo
2010-10-01 00:46:01
A:
This will also work:
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '(.*?)~', '$1' . $replace . '$2', $subject, 1);
}
UPDATE Slightly more concise version (http://ideone.com/B8i4o):
function str_lreplace($search, $replace, $subject)
{
return preg_replace('~(.*)' . preg_quote($search, '~') . '~', '$1' . $replace, $subject, 1);
}
Alix Axel
2010-10-01 07:43:50
Am i doing it wrong ? If so just ignore me :) ||| echo str_lreplace("x", "y", "this x or that x"); => Output: "y" See: http://www.ideone.com/UXuTo
edorian
2010-10-01 07:50:18
@edorian: Oops! Sorry, I posted that in a hurry, the correct version is here: http://ideone.com/vR073.
Alix Axel
2010-10-01 18:36:44