88 of 410 menu

The strrpos Function

The strrpos function returns the position of the last occurrence of a substring.

The result of the function will be the position of the first character of the found substring, and if such a substring is not found - ⁅с⁆false⁅/с⁆.

The start of the search can be adjusted with a third optional parameter - if specified, the search will start not from the beginning of the string, but from the specified location.

Syntax

strrpos(string $haystack, string $needle, int $offset = 0): int|false

Example

In this example, the function will return the position of the last occurrence of the character 'a':

<?php echo strrpos('abcde abcde', 'a'); ?>

Code execution result:

6

Example

Search for the last occurrence of a multi-character substring:

<?php echo strrpos('hello world, hello php', 'hello'); ?>

Code execution result:

13

Example

Search with a specified start position:

<?php echo strrpos('abcabcabc', 'a', 5); ?>

Code execution result (search starts from position 5):

6

Example

If the substring is not found, the function returns false:

<?php var_dump(strrpos('abcdef', 'z')); ?>

Code execution result:

false

Example 5: Case-Sensitive Search

The function is case-sensitive:

<?php var_dump(strrpos('Hello World', 'h')); ?>

Code execution result:

false

See Also

  • the strripos function,
    which performs a similar operation case-insensitively
  • the strpos function,
    which returns the position of the first occurrence of a substring
  • the str_contains function,
    which checks for the occurrence of a character in a string
  • the str_starts_with function,
    which checks the beginning of a string
  • the str_ends_with function,
    which checks the end of a string
byenru