PHP strrpos() Tutorial 🎯

beginner
6 min

PHP strrpos() Tutorial 🎯

Welcome to our comprehensive guide on the PHP strrpos() function! This function will help you find the position of a substring in a given string, starting from the end. Let's dive in!

Understanding the basics πŸ“

Before we delve into strrpos(), let's first understand some basics:

  • Strings: In PHP, strings are sequences of characters. They are enclosed in single quotes (') or double quotes (").

What is strrpos()? πŸ’‘

The strrpos() function returns the position of the last occurrence of a substring in a given string. It's similar to strpos(), but it starts the search from the end of the string.

Syntax πŸ“

php
int strrpos(string haystack, string needle, int offset = 0)
  • haystack: The string to be searched.
  • needle: The substring to be found.
  • offset (optional): The position from the end of the haystack to start the search. Default is 0, meaning the search starts from the very end.

Example 1: Basic Usage βœ…

Let's find the position of the last occurrence of 'n' in the string 'Hello World!'.

php
<?php $str = "Hello World!"; $position = strrpos($str, 'n'); echo $position; // Output: 6 ?>

In this example, we searched for the letter 'n' in the string 'Hello World!'. The strrpos() function found it at the 6th position (index 5, as counting starts from 0) from the end.

Example 2: With Offset βœ…

Let's find the position of the last occurrence of 'l' in the string 'Hello World!', but this time starting the search from the 4th position from the end.

php
<?php $str = "Hello World!"; $position = strrpos($str, 'l', 4); echo $position; // Output: 3 ?>

In this example, we started the search for 'l' from the 4th position from the end. The strrpos() function found it at the 3rd position (index 2, as counting starts from 0) from the end.

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the PHP `strrpos()` function do?

By now, you should have a good understanding of the PHP strrpos() function. Happy coding! πŸ€–