Monday, January 31, 2011

lastIndexOf In PHP

While there is strripos in PHP5, PHP4 doesn't have a pre-built function. Consider the following.
$string="01234567890123456789";
$item="3456";
$index=strpos(strrev($string),strrev($item));
$index=strlen($string)-strlen($item)-$index;
echo $index;
//result 13
In the string, $string, we want to find the last occurrence of $item, "3456". To do this, we reverse both strings using strrev(). Then we search for the string and find its position. Because the strings have been reversed, we need to compute the actual last position of the substring, $item, in the string, $string. To do this, we use the function strlen().
The following is an example of a function that finds the last occurrence of a string in a string:
function lastIndexOf($string,$item){
    $index=strpos(strrev($string),strrev($item));
    if ($index){
        $index=strlen($string)-strlen($item)-$index;
        return $index;
    }
        else
        return -1;
}

$string="01234567890123456789";
$item="3456";
echo lastIndexOf($string,$item);

//result 13

echo "
";
$item="elephant";
echo lastIndexOf($string,$item);

//result: -1

3 comments:

Unknown on August 7, 2011 at 12:42 AM said...

Thanks.. that was a quick tool.. saved my time! :)

Seth Caldwell on April 20, 2012 at 3:12 PM said...

why not use strrpos?

Originative on April 24, 2012 at 1:08 AM said...

please see the first line of this tutorial...

Post a Comment

 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems