Monday, 2 February 2015

Find Position Of Nth Occurrence Of String

Find Position Of Nth Occurrence Of String

The PHP strpos function and its relatives will find the first or last occurance of a string within a string. This is useful for using with functions such as substr() to get portions of strings for other purposes. However, there is no PHP function currently to get the position of the Nth occurance of a string. If you wanted to find the position of th e second occurance of a string within a string, or find the tenth occurance of a string within a string, this function will provide it.
By adding an offset to the function, a search can be made on as string using as search string and the numerical position of that occurance is returned.

<?php
/**
 *
 * @Find position of Nth occurance of search string
 *
 * @param string $search The search string
 *
 * @param string $string The string to seach
 *
 * @param int $offset The Nth occurance of string
 *
 * @return int or false if not found
 *
 */
function strposOffset($search$string$offset)
{
    
/*** explode the string ***/
    
$arr explode($search$string);
    
/*** check the search is not out of bounds ***/
    
switch( $offset )
    {
        case 
$offset == 0:
        return 
false;
        break;
    
        case 
$offset max(array_keys($arr)):
        return 
false;
        break;

        default:
        return 
strlen(implode($searcharray_slice($arr0$offset)));
    }
}
?>

EXAMPLE USAGE

Note in this example that the search string "is" occurs four times within the string to be searched. Two time as the word "is" and two times within the word "this". The third occurnce is at position 27 in the string.

<?php
/*** the third occurance ***/$offset 3;
/*** the string to search for ***/$search 'is';
/*** the string to search ***/$string 'this is not a love song, this is not a love song';

echo 
strposOffset($search$string$offset);?>

0 comments:

Post a Comment