PHP StartsWith and EndsWith functions with optional case senstive

It seems that the default PHP library doesn’t have an implementation for functions that tests for the existence of a sub string at the start or end of a larger string, so here they are:

Those functions accept an optional 3rd argument to choose whether to match the string with case sensitive or case insensitive comparison.

By default, the matching will be case sensitive.

 
function StartsWith($haystack, $needle, $case=true)
{
    $len = strlen($needle);
    if ($len == 0) {
        return true;
    } else {
        if ($case)
            return (substr($haystack, 0, $len) === $needle);
        else
            return (strcasecmp(substr($haystack, 0, $len), $needle) === 0);
    }
}
 
function EndsWith($haystack, $needle, $case=true)
{
    $len = strlen($needle);
    if ($len == 0) {
        return true;
    } else {
        if ($case)
            return (substr($haystack, -$len) === $needle);
        else
            return (strcasecmp(substr($haystack, -$len), $needle) === 0);
    }
}

Example usage:

var_dump(StartsWith("codeground.net", "code"));
var_dump(EndsWith("codeground.net", "net"));
 
var_dump(StartsWith("codeground.net", "Code", true));
var_dump(EndsWith("codeground.net", "neT", false));

This above will print

bool(true)
bool(true)
bool(false)
bool(true)

You will notice also that when you input an empty string for the “$Needle” variable, the output will be true, which is same behavior of the .NET (C#, VB.NET, ..etc) behavior of string.StartsWith(), and string.EndsWith() functions.

Leave a Reply

Your email address will not be published. Required fields are marked *

(Your message will only be visible after moderation)