Wednesday, September 5, 2012

PHP startsWith() and endsWith() functions, Check String Ending/ Starting with a Character


PHP startsWith() and endsWith() functions, Check String Ending/ Starting with a Character 

Q:

I need 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


Solution :

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.

:D
Steel facing probs ? let me know by comments !

Know More About :
PHP Freelancing India

Reactions:

3 comments:

  1. Thanks for sharing those informations that giving us a lot of ideas on doing PHP functions. This must be very helpful and every php programmer can use this content.

    ReplyDelete
  2. Bhavin Rana is a Professional & Experianced Freelance Developer From India.Thanks for sharing it.

    PHP Development India

    ReplyDelete

Any Questions or Suggestions ?

About

Professional & Experienced Freelance Developer From India, Technologist, Software Engineer, internet marketer and Open Sources Developer with experience in Finance, Telecoms and the Media. Contact Me for freelancing projects.

Enter your email address:

Delivered by FeedBurner

PHP Freelancer India - Google+