|
deep inside webpages
 


Replace last occurance of a String - PHP

Replacing part of a string with another string is straight forward, but what if you have to replace last occurrence of a character or string with another string.

Here is the fastest way to do this.

  1. function str_replace_last( $search , $replace , $str ) {
  2.     if( ( $pos = strrpos( $str , $search ) ) !== false ) {
  3.         $search_length  = strlen( $search );
  4.         $str    = substr_replace( $str , $replace , $pos , $search_length );
  5.     }
  6.     return $str;
  7. }
PHP Code

The first argument
$search
keeps the string to be searched for,
$replace
is the replacement string and
$str
is the subject string, commonly known as haystack.

Usage

  1. $str       = 'My Name is John.';
  2. $search    = 'John';
  3. $replace   = 'Peter';
  4. echo str_replace_last( $search , $replace , $str );
  5.  
  6. //Result
  7. My Name is Peter.
PHP Code

In case the
$search
is not found inside the
$str
, the function returns the original untouched string
$str
. This behavior is compatible with the default behavior of
str_replace
PHP's builtin function that replaces all occurrances of a string inside another string.



  1. Number-to-Word Conversion with PHP
  2. Remove undesired characters with trim_all() - PHP
  3. How to validate ASCII Text - PHP
  4. register_globals is Back - PHP Implementation
  5. Faster Random Numbers with PHP