Monday, February 7, 2011

StartsWith in PHP

PHP does not provide a native function to check whether a string starts 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 startsWith($haystack,$needle,$isCaseSensitive){
        if($isCaseSensitive){
            return strcmp($needle, substr($haystack, 0,strlen($needle))) == 0?true:false;
        }else{
           return strcasecmp($needle, substr($haystack, 0,strlen($needle))) == 0?true:false;
        }
    }
Concept of function is fairly simple we first just get the substring of the haystack to of the length of the needle 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