29

strpos function in reverse

I would like to find a method where i can find a character position in reverse.For example last "e" starting count in reverse.

From example

$string="Kelley";
$strposition = strpos($string, 'e');

it will give me position 1.

Baba
  • 94,024
  • 28
  • 166
  • 217
  • 4
    Welcome to Stack Overflow! Not to discourage you too much from asking, but always remember to Google first - when searching for `strpos function in reverse in php`, `strrpos()` turns up in third place for me. Thanks! – Pekka Oct 21 '12 at 20:02
  • 4
    I had the same problem, I googled, came here, found answer, happy – Allisone Nov 18 '13 at 00:13

8 Answers8

45
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

Find the numeric position of the last occurrence of needle in the haystack string.

http://php.net/manual/en/function.strrpos.php

Manuel Schweigert
  • 4,884
  • 4
  • 20
  • 32
11

What you need is strrpos to find the position of the last occurrence of a substring in a string

$string = "Kelley";
$strposition = strrpos($string, 'e');
var_dump($strposition);
Baba
  • 94,024
  • 28
  • 166
  • 217
8

strripos and strrpos add $needle length to result, eg.:

<?php
$haystack = '/test/index.php';
$needle   = 'index.php';

echo strrpos($haystack, $needle);//output: 6

An alternative is use strrev for retrieve position from the end, eg:

<?php
$haystack = 'Kelley';
$needle   = 'e';

echo strpos(strrev($haystack), strrev($needle));//Output: 1
Protomen
  • 9,471
  • 9
  • 57
  • 124
  • I think this is closer to the answer that they were looking for. The only difference would be to get the actual position in the original string, you would need to subtract the found position from the length of the original string. In the provided example the "e" just happens to be in the same position from the start as the beginning. – nickbwatson Aug 05 '22 at 16:16
7

Try this:

strrpos()

Hope that helps.

tobspr
  • 8,200
  • 5
  • 33
  • 46
2

Simply as can be: strrpos()

This will return the first occurence of the character from the right.

Sven
  • 132
  • 1
  • 10
1
function rev ($string, $char)
{
    if (false !== strrpos ($string, $char))
    {
        return strlen ($string) - strrpos ($string, $char) - 1;
    }
}

echo rev ("Kelley", "e");
akond
  • 15,865
  • 4
  • 35
  • 55
1

Simple function , you can add:

    function stripos_rev($hay,$ned){
    $hay_rev = strrev($hay);
    $len = strlen($hay);
    if( (stripos($hay_rev,$ned)) === false ){
        return false;
    } else {
        $pos = intval(stripos($hay_rev,$ned));
        $pos = $len - $pos;
    }
    return $pos;

}
sameerNAT
  • 95
  • 1
  • 3
0

The only solution that works is this function:

function strpos_reverse ($string, $search, $offset){
    return strrpos(substr($string, 0, $offset), $search);
}