Replace the last string occurence

This function replaces the last string occurrence in a given text with the specified string. This is may be an alternative for preg_replace() function

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?

 

function str_replace_last($string ,$search , $replace){

 

if ((($string_len=strlen($string))==0) || (($search_len=strlen($search))==0)) return $string;

$pos=strrpos($string,$search);

if ($pos>0) return substr($string,0,$pos).$replace.substr($string,$pos+$search_len,max(0,$string_len-($pos+$search_len)));

return $string;

}

 

//Usage example

 

$text="I love apples. I love bananas.";

echo str_replace_last($text,"love" , "don't love");

 

//The result:

//I love apples. I don't love bananas.

?>

Newsletter

Sign up for inspiration, news and updates