Wednesday, February 9, 2011

EndsWith in PHP

PHP does not provide a native function to check whether a string ends with a specific string or not, to do this functionality we have to write a very simple function of our own. The concept of this function is fairly simple, we need two strings say one is haystack and other is needle and one boolean to check whether we want case-sensitive comparison on strings or not, our function would be like this,
  public function endsWith($haystack,$needle,$isCaseSensitive){
        if($isCaseSensitive){
            return strcmp($needle, substr($haystack, -1*strlen($needle))) == 0?true:false;
        }else{
           return strcasecmp($needle, substr($haystack, -1*strlen($needle))) == 0?true:false;
        }
  }
Concept of function is fairly simple we first just get the substring of the haystack to the length of the needle(we multiply this length with -1 so that we get substring from the end of the haystack) and then check whether our substring returned is equal to our needle or not

0 comments:

Post a Comment

 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems