Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);
Using replace() function. In Python, the string class provides a function replace(), and it helps to replace all the occurrences of a substring with another substring. We can use that to replace only the last occurrence of a substring in a string.
strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .
To replace the first occurrence of a character in Java, use the replaceFirst() method.
You can use this function:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
Another 1-liner but without preg:
$subject = 'bourbon, scotch, beer';
$search = ',';
$replace = ', and';
echo strrev(implode(strrev($replace), explode(strrev($search), strrev($subject), 2))); //output: bourbon, scotch, and beer
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result); //output: this is my world, not my farm
The following rather compact solution uses the PCRE positive lookahead assertion to match the last occurrence of the substring of interest, that is, an occurrence of the substring which is not followed by any other occurrences of the same substring. Thus the example replaces the last 'fox'
with 'dog'
.
$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);
OUTPUT:
The quick brown fox, fox, fox jumps over the lazy dog!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With