startsWith() and endsWith() functions in PHP

masterjosh
by
masterjosh
Mar 20, 2019
startsWith() and endsWith() functions in PHP

It is possible to use strrpos and strpos to check start-with and ends-with respectively.

Note that using 


strrpos

 to check starts with and 


strpos

 to check ends with will return as soon as possible instead of checking the whole string till the end. Also, this solution does not create a temporary string. Consider explaining the reason before downvoting. Just because a f-wit at the DWTF doesn't understand how this function works or thinks there is only one solution doesn't mean this answer is wrong.


function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === ''
      || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}
function endsWith($haystack, $needle) {
    // search forward starting from end minus needle length characters
    if ($needle === '') {
        return true;
    }
    $diff = \strlen($haystack) - \strlen($needle);
    return $diff >= 0 && strpos($haystack, $needle, $diff) !== false;
}

Tests and results (compare with this):


startsWith('abcdef', 'ab') -> true
startsWith('abcdef', 'cd') -> false
startsWith('abcdef', 'ef') -> false
startsWith('abcdef', '') -> true
startsWith('', 'abcdef') -> false
endsWith('abcdef', 'ab') -> false
endsWith('abcdef', 'cd') -> false
endsWith('abcdef', 'ef') -> true
endsWith('abcdef', '') -> true
endsWith('', 'abcdef') -> false

Note: the 

strncmp and substr_compare

 functions will outperform this function.




Add Comment