String StartsWith and EndsWith in PHP

The following are a simple implementation checking whether a string starts or ends with another string in PHP.

function str_starts_with($haystack, $needle)
{
    return strpos($haystack, $needle) === 0;
}
function str_ends_with($haystack, $needle)
{
    return strrpos($haystack, $needle) + strlen($needle) ===
        strlen($haystack);
}

$start = 'http';
$end = 'com';
$str = 'http://google.com';
str_starts_with($str, $start); // TRUE
str_ends_with($str, $end); // TRUE

Note that we need triple equals sign (===) since strpos() may return FALSE, while FALSE == 0 is actually TRUE.

The above approach is not efficient for large strings. It runs in O(n) time. The following approach is better; it runs in constant time.

function str_starts_with($haystack, $needle)
{
    return substr_compare($haystack, $needle, 0, strlen($needle)) 
           === 0;
}
function str_ends_with($haystack, $needle)
{
    return substr_compare($haystack, $needle, -strlen($needle)) 
           === 0;
}

The syntax of substr_compare() is as below:
int substr_compare(string $main_str, string $str, int $offset [, int $length [, bool $case_insensitivity = false ]])
substr_compare() compares main_str from position offset with str up to length characters.

Related Posts

Comments

comments