PHP – String startsWith and endsWith

The following 2 functions could check if a string starts/ends with another string.

/* Return TRUE if $needle is empty */
function startsWith($haystack, $needle) {
  $length = strlen($needle);
  return (substr($haystack, 0, $length) === $needle);
}

/* Return TRUE if $needle is empty */
function endsWith($haystack, $needle) {
  $length = strlen($needle);
  if ($length == 0) {
    return TRUE;
  }
  $start  = $length * -1;
  return (substr($haystack, $start) === $needle);
}

Please note that if the $needle is empty, both functions will return TRUE.

Done =)

Reference: StackOverflow – PHP startsWith() and endsWith() functions

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.