RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.74% (6.40%*) • Investment PI: 5.49% (6.32%*)

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.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment