Saturday, September 25, 2010

No of occurrences of substring in a string.

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($search, array_slice($arr, 0, $offset)));

    }
}


$offset = 2;

/*** the string to search for ***/
$search = 'is';

/*** the string to search ***/
$string = 'this is a best way to get no of occurrences of a substring in a string ';

echo $p= strposOffset($search, $string, $offset);
if($p=='')
echo 'not found'
?>

No comments:

Post a Comment