What is strrpos()?

strrpos() is a string function in PHP used to find the position of the last occurrence of a substring (needle) in a string (haystack).

strrpos(string $haystack, string $needle)

strrpos(string $haystack, string $needle, int $offset)

$str = “https://www.example.com/track?code=12345”;

$pos = strrpos($str, '=');
echo $pos; // Output: 36 (position of the last "=")

Why use it?

To extract data after the last special character (like = or /).

What does it return?

  • Returns the position (as integer) of the last occurrence.
  • Returns false if the substring is not found.

Important:

Always use === false in conditionals to distinguish between “not found” and position 0:

if (strrpos($str, '=') !== false) {
    echo "Found";
}

Use Cases:

  1. Get value after last = in a URL.
  2. Check last delimiter like /, -, _ in a path or slug.
  3. Validate format by checking positions of expected characters.

Advantages (Merits):

  • Finds the last match (more precise than strpos() in some cases).
  • Simple to use, lightweight.
  • Works well for parsing URLs, file paths, and query strings.

Alternatives:

FunctionDescriptionstrpos()Finds first occurrencestrrchr()Returns last part of string from characterstrstr()Returns part of string from first occurrencesubstr()Extracts string using position (often used with strrpos)

<?php

$url = "https://track.com/parcel?code=12345";
if (strrpos($url, '=') !== false) {
    $code = substr($url, strrpos($url, '=') + 1);
    echo "Tracking Code: " . htmlspecialchars($code);
} else {
    echo "Full URL: " . htmlspecialchars($url);
}
?>

This prints just the tracking number if the = is found, else prints the whole URL.

Would you like a visual code snippet or example in a Magento .phtml template?

Leave a comment

Your email address will not be published. Required fields are marked *