This snippet will enable you to check if a string ends with a certain string. Particularly very handy when checking filetypes, like is something a jpg or not.
The third parameter is optional, if set to true then the comparison will be case-specific.
function endsWith($haystack,$needle,$case=true) { //If its case specific if($case){ return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0); } return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0); }
Sample Code
if(endsWith("hello.jpg", '.jpg')) { print "true"; } else { print "false"; } //True
Here strcmp
plays major role which compare two strings and returns < 0 if string1
is less than string2
; > 0 if string1
is greater than string2
, and 0 if they are equal.
Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.