PHP – Find the last occurrence of a needle within a haystack using the iconv_strrpos() function

In PHP, the iconv_strrpos() function is used to find the last occurrence of a needle within a haystack. This function returns the character position of the last match in a string, supporting various character encodings.

Syntax

iconv_strrpos(string $haystack, string $needle, ?string $encoding = null): int|false

Parameters

iconv_strrpos() accepts three parameters: $haystack, $needle and $encoding.

  • $haystack − The whole string to search within.

  • $needle − The substring to search for in the haystack.

  • $encoding − The character encoding. If omitted or null, uses iconv.internal_encoding.

Return Values

iconv_strrpos() returns the numeric position of the last occurrence of the needle in the haystack. If the needle is not found, the function returns false.

Note: From PHP 8.0, encoding is nullable. From PHP 7.1, negative offsets are supported.

Example 1: Basic Usage

<?php
    // UTF-8 string
    $position = iconv_strrpos("hello world!", "l", "UTF-8");
    var_dump($position);
    
    // Not found case
    $notFound = iconv_strrpos("hello world!", "x", "UTF-8");
    var_dump($notFound);
?>
int(9)
bool(false)

Example 2: Multiple Occurrences

<?php
    // Finding last occurrence of 'o'
    $text = "Good morning to everyone";
    $lastO = iconv_strrpos($text, "o", "UTF-8");
    echo "Last 'o' found at position: " . $lastO . "<br>";
    
    // Compare with first occurrence
    $firstO = iconv_strpos($text, "o", "UTF-8");
    echo "First 'o' found at position: " . $firstO;
?>
Last 'o' found at position: 14
First 'o' found at position: 1

Conclusion

The iconv_strrpos() function is useful for finding the last position of a substring in multi-byte encoded strings. It returns the position as an integer or false if not found.

Updated on: 2026-03-15T09:56:26+05:30

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements