Thursday 13 October 2016

PHP - Functions to find strings inside other strings.

<?php

/*------------------------------------------------------------------------------
|| |Description:
| Functions to find strings inside other strings.
|------------------------------------------------------------------------------*/

// InStr function
// checks for an occurance of a string
// within another string
function InStr($String,$Find,$CaseSensitive = false)
{
    $i=0;
    while(strlen($String) >= $i)
    {
        unset($substring);
        if($CaseSensitive)
        {
            $Find = strtolower($Find);
            $String = strtolower($String);
        }
        $substring = substr($String,$i,strlen($Find));
        if($substring == $Find) return true;
        $i++;
    }
    return false;
}

// A similar function, returns the number of occurances
function InStrCount($String,$Find,$CaseSensitive = false)
{
    $i = 0;
    $x = 0;
    while(strlen($String) >= $i)
    {
        unset($substring);
        if($CaseSensitive)
        {
            $Find = strtolower($Find);
            $String = strtolower($String);
        }
        $substring = substr($String,$i,strlen($Find));
        if($substring == $Find) $x++;
        $i++;
    }
    return $x;
}

// Another similar function, this will return the position of
// the string. returns -1 if the string does not exist
function InStrPos($String,$Find,$CaseSensitive = false)
{
    $i = 0;
    while(strlen($String) >= $i)
    {
        unset($substring);
        if($CaseSensitive)
        {
            $Find = strtolower($Find);
            $String = strtolower($String);
        }
        $substring = substr($String,$i,strlen($Find));
        if($substring == $Find) return $i;
        $i++;
    }
    return -1;
}

//Example
echo InStrPos("wel come","come");  // 4

0 comments:

Post a Comment