W3docs

strrchr()

The strrchr() function in PHP is used to find the last occurrence of a character or substring in a string. It returns the portion of the string that starts with

Introduction

The strrchr() function in PHP is used to find the last occurrence of a character in a string. It returns the portion of the string that starts with the last occurrence of that character and ends with the end of the string. In this article, we will discuss the strrchr() function in detail and how it can be used in PHP.

Understanding the strrchr() function

The syntax for using the strrchr() function in PHP is as follows:

The PHP syntax of the strrchr()

strrchr(string $haystack, string $needle) : string|false

Here, $haystack is the string in which we want to search for the $needle character. The $needle parameter can be a string, but only its first character is used for the search.

The strrchr() function searches the $haystack string for the last occurrence of the $needle character. If the character is found, the function returns the portion of the string that starts with that occurrence and ends with the end of the string. If the character is not found, the function returns false.

Example Usage

Here is an example usage of the strrchr() function in PHP:

Example of PHP strrchr()

<?php

$string = "Hello World";
$search = "o";

$result = strrchr($string, $search);

if ($result !== false) {
  echo "Found last occurrence of '$search' in '$string': '$result'";
} else {
  echo "Did not find '$search' in '$string'";
}

In the example above, we define a string $string and a search character $search. We then use the strrchr() function to find the last occurrence of the $search character in the $string. Since the character is found, the output will be "Found last occurrence of 'o' in 'Hello World': 'o World'".

Conclusion

The strrchr() function in PHP is a useful tool for finding the last occurrence of a character in a string. It can be used in situations where a specific character needs to be located near the end of a string. By understanding how to use the strrchr() function, developers can create more efficient and effective PHP applications.

Practice

Practice

What is the function of the strrchr() function in PHP?