startsWith() and endsWith() functions in PHP


How can I write two functions that would take a string and return if it starts with the specified character/string or ends with it?

For example:

$str = '|apples}';

echo startsWith($str, '|'); //Returns true
echo endsWith($str, '}'); //Returns true
2/3/2018 4:31:37 PM

Accepted Answer

function startsWith($haystack, $needle)
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);

function endsWith($haystack, $needle)
    $length = strlen($needle);
    if ($length == 0) {
        return true;

    return (substr($haystack, -$length) === $needle);

Use this if you don't want to use a regex.

8/17/2018 1:51:41 PM

You can use substr_compare function to check start-with and ends-with:

function startsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, 0, strlen($needle)) === 0;
function endsWith($haystack, $needle) {
    return substr_compare($haystack, $needle, -strlen($needle)) === 0;

This should be one of the fastest solutions on PHP 7 (benchmark script). Tested against 8KB haystacks, various length needles and full, partial and no match cases. strncmp is a touch faster for starts-with but it cannot check ends-with.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow