PHP – mb_strrichr() function

The mb_strrichr() function in PHP is used to find the last occurrence of a character in a string within another string. This function is case-insensitive, unlike mb_strrchr(). This function finds the last occurrence of a needle in the given haystack string and returns that portion of the haystack. It returns false if a needle is not found in the haystack string.

Syntax

string mb_strrichr(
   $str_haystack,
   $str_needle,
   $bool_before_needle=false,
   $str_encoding
)

Parameters

mb_strrichr() accepts the following four parameters −

  • str_haystack − The string from which to get the last occurrence of the needle.

  • str_needle − The string that is to be searched in the haystack.

  • before_needle − It is used to decide which portion of the haystack to return.

    • If it is set to True, then it returns all the haystack from the starting to the last occurrence of the needle.

    • If it is set to False, then it returns all the haystack string from the last occurrence of the needle to the end.

  • str_encoding − It is the character encoding name to use. If encoding is omitted, then the internal encoding is used.

Return Values

This string function returns the specified portion from the haystack string or it returns False if a needle is not found in the haystack string.

Example 1: Basic Usage with before_needle = false

<?php
   // String is Hello World
   // Needle "rl" is used
   // before_needle is false (default)
   $string = mb_strrichr("HelloWorld", "rl", false, "UTF-8");

   // Output will be string(3) "rld"
   var_dump($string);
?>
string(3) "rld"

Example 2: Using before_needle = true

<?php
   // String is Hello World  
   // Needle "rl" is used
   // before_needle is set true
   $string = mb_strrichr("Hello World", "rl", true, "UTF-8");

   // Output will be string(8) "Hello Wo"
   var_dump($string);
?>
string(8) "Hello Wo"

Example 3: When Needle is Not Found

<?php
   // String is Hello World
   // Needle "ef" is not found in the haystack
   // Hence it will return false
   $string = mb_strrichr("Hello World", "ef", true, "UTF-8");

   // Output will be false
   var_dump($string);
?>
bool(false)

Example 4: Case-Insensitive Behavior

<?php
   // Demonstrating case-insensitive search
   $string = mb_strrichr("Hello World", "RL", false, "UTF-8");
   
   // Even though we search for "RL" (uppercase), it finds "rl" (lowercase)
   var_dump($string);
?>
string(3) "rld"

Conclusion

The mb_strrichr() function is useful for case-insensitive string searching from the end of a string. The before_needle parameter controls whether you get the portion before or after the found needle, making it flexible for various string manipulation tasks.

Updated on: 2026-03-15T10:01:45+05:30

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements