Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last occurrence of a string in a string

People also ask

How do I change the last occurrence of a string in Java?

Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);

How do I change the last occurrence of a string in Python?

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.

How do you find the last occurrence of 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 .

How do you replace only one occurrence of a string in Java?

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!!!