简体   繁体   中英

strpos function in reverse in php

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.

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

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);

Try this:

strrpos()

Hope that helps.

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

Simply as can be: strrpos()

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

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

echo rev ("Kelley", "e");

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM