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

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s