OneBite.Dev - Coding blog in a bite size

Find The Position Of The Last Occurrence Of A Substring In A String In PHP

Code snippet for how to Find The Position Of The Last Occurrence Of A Substring In A String In PHP with sample and detail explanation

In PHP, finding the position of the last occurrence of a substring in a string can be invaluable when working with large data sets or sorting through text. This operation can be performed easily using PHP’s built-in function strrpos().

Code snippet for Finding the Last Occurrence of a Substring

Below is a simple code snippet to illustrate the use of strrpos() function in PHP:

<?php
$string = "Lorem ipsum dolor sit amet, ipsum dolor sit.";
$substring = "ipsum";

$position = strrpos($string, $substring);

echo "The last occurrence of '" . $substring . "' is at position: " . $position;
?>

Code Explanation for Finding the Last Occurrence of a Substring

Now, let us go step by step to explain how the code works:

  1. We start by defining a string named $string, which would serve as our main text. Then, we define the substring $substring that we are searching for within the main string.

    $string = "Lorem ipsum dolor sit amet, ipsum dolor sit.";
    $substring = "ipsum";
  2. The strrpos() function is then called with two arguments - the first one being the string in which to find the substring, and the second one being the substring itself. The strrpos() function will return the position of the last occurrence of the substring in the string. If the substring is not found, the function will return FALSE.

    $position = strrpos($string, $substring);
  3. Finally, the position of the last occurrence of the substring is echoed out. If the substring is not found, this will display FALSE.

    echo "The last occurrence of '" . $substring . "' is at position: " . $position;

Through this example, we can see how to find the last occurrence of a substring in a string in PHP using the strrpos() function. It can be very useful in tasks like text processing, search functionality, and much more. To use it efficiently, always remember that the starting point of string indexing in PHP is 0, not 1. That means the first character in the string is at position 0.

php