Quick Tip: Replace Last Occurrence of a String In PHP

Posted June 29, 2009 @ 11:27am by Phil

A variation of the str_replace function provided in PHP where only the last occurrence of the string is replaced. This function has come in handy for me a few times.

<?php
  function str_lreplace ($search, $replace, $subject)
  {
    return substr_replace($subject, $replace, strrpos($subject, $search), strlen($search));
  }
?>

Download Source: str_lreplace.php

Tags: PHP/MySQL, Quick Tip