How to replace last occurrence of a string in php?

Mayank
Mayank
Member
194 Points
12 Posts

Anyone know of a very fast way to replace the last occurrence of a string with another string in a string in PHP?

Thanks..

Views: 11526
Total Answered: 1
Total Marked As Answer: 0
Posted On: 28-May-2017 04:56

Share:   fb twitter linkedin
Answers
Jak
Jak
Member
858 Points
132 Posts
         

Following will just  replace the last occurrence of a substring inside of a string, you can copy this function into you code:

function lastReplace($search, $replace, $subject){
       $pos = strrpos($subject, $search);
       if($pos !== false){
           $subject = substr_replace($subject, $replace, $pos, strlen($search));
       }
       return $subject;
}
Posted On: 24-Nov-2017 22:32
strrpos() method returns the position of the last occurrence in a string
 - Jak  24-Nov-2017 22:35
 Log In to Chat