PHP-function: Does $string ends with… #HelpMeCode

Hi guys

I decided to upload a quick post on my blog, every time somebody asks me for a code example. I call it #HelpMeCode πŸ™‚

So I was just asked on an IRC channel, how to detect if a string in PHP ends with something specific. I’ve created this simple function to solve this.

The function needs two inputs, haystack and needle.

🚜 The Haystack is the string we’re searching in, for example, “I love Daniel”.
πŸ“Β The Needle is the stuff we are looking for, for example, “Daniel”.

If we ran the function with endsWith(“I love Daniel“,”Daniel“); it would return true.

If we ran the function like this endsWith(“I love Daniel“,”Kenny“); it would return false.

That’s it. Pretty simple. 😎 And here’s the code:

 function endsWith($haystack, $needle) { if ($needle === '') { return true; } // Search forward, starting from end minus the length of var $needle $diff = \strlen($haystack) - \strlen($needle); return $diff >= 0 && strpos($haystack, $needle, $diff) !== false; } 

Need a function? Ask me! I can certainly help.Β πŸ™

Views:
517
Article Categories:
CodingPHP

Leave a Reply

Your email address will not be published. Required fields are marked *