Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Replace The Last Occurrence Of a Character With PHP

In a recent project I had a need to replace the last occurrence of a character in a string with another string. While our first function works as intended, following are some others that we found on stackoverflow that also do as we intended. They're reproduced here for your benefit and as a reference for our team.

■ ■ ■

1
<?php 
2
/*
3
    Replace the last occurence of a charater (in a string) with PHP
4
    http://www.beliefmedia.com/code/php-snippets/replace-last-occurrence-string
5
*/
6
 
7
function beliefmedia_str_lreplace($string, $find, $replace) {
8
  if (strpos($string, $find) === false) return $string;
9
  $string = strrev(implode(strrev($replace), explode(strrev($find), strrev($string), 2)));
10
 return $string;
11
}

1
<?php 
2
/*
3
    Replace the last occurence of a charater (in a string) with PHP
4
    http://www.beliefmedia.com/code/php-snippets/replace-last-occurrence-string
5
*/
6
 
7
 
8
function beliefmedia_str_lreplace($string, $find, $replace) {
9
  $pos = strrpos($string, $find);
10
  if ($pos === false) return $string;
11
  $string = substr_replace($string, $replace, $pos, strlen($find));
12
 return $string;
13
}

1
<?php 
2
/*
3
    Replace the last occurence of a charater (in a string) with PHP
4
    http://www.beliefmedia.com/code/php-snippets/replace-last-occurrence-string
5
*/
6
 
7
 
8
function beliefmedia_str_lreplace($string, $find, $replace) {
9
  return preg_replace("/($find(?!.*$find.*))/", $replace, $string);
10
}

Usage

Example:

1
$string = 'cat, dog, frog, cow';
2
$find = ','; $replace = ', and';
3
 
4
echo beliefmedia_str_lreplace($string, $find, $replace);

returns: cat, dog, frog, and cow.

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment