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

Example Interest Rates: Home Loan Variable: 2.54% (2.74%*) • Home Loan Fixed: 3.74% (3.8%*) • Fixed: 2.48% (2.94%*) • Variable: 2.54% (2.74%*) • Investment IO: 2.3% (3.76%*) • Investment PI: 2.04% (3.8%*)

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
function beliefmedia_str_lreplace($string, $find, $replace) {
8
  $pos = strrpos($string, $find);
9
  if ($pos === false) return $string;
10
  $string = substr_replace($string, $replace, $pos, strlen($find));
11
 return $string;
12
}
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
  return preg_replace("/($find(?!.*$find.*))/", $replace, $string);
9
}

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.

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  AUS Eastern Standard Time (Washington)

  Want to have a chat?
 

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