strpos function in reverse in php
Asked Answered
D

8

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.

Dichroite answered 21/10, 2012 at 19:57 Comment(2)
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!Tuber
I had the same problem, I googled, came here, found answer, happyLydgate
F
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

Farmyard answered 21/10, 2012 at 20:0 Comment(0)
L
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);
Liggitt answered 21/10, 2012 at 20:0 Comment(0)
S
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
Smack answered 3/5, 2015 at 6:48 Comment(1)
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.Cannonade
E
7

Try this:

strrpos()

Hope that helps.

Edita answered 21/10, 2012 at 20:0 Comment(0)
O
2

Simply as can be: strrpos()

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

Optimism answered 21/10, 2012 at 20:1 Comment(0)
M
1
function rev ($string, $char)
{
    if (false !== strrpos ($string, $char))
    {
        return strlen ($string) - strrpos ($string, $char) - 1;
    }
}

echo rev ("Kelley", "e");
Macaw answered 21/10, 2012 at 20:2 Comment(0)
L
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;

}
Lifeblood answered 21/1, 2018 at 4:42 Comment(0)
B
0

The only solution that works is this function:

function strpos_reverse ($string, $search, $offset){
    return strrpos(substr($string, 0, $offset), $search);
}
Borax answered 18/6, 2021 at 19:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.