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: