Starts with

Tests if a text starts with an given string.

/**
 * StartsWith
 * Tests if a text starts with an given string.
 *
 * @param     string
 * @param     string
 * @return    bool
 */
function StartsWith($Haystack, $Needle){
    // Recommended version, using strpos
    return strpos($Haystack, $Needle) === 0;
}
 
// Another way, using substr
function StartsWithOld($Haystack, $Needle){ 
    return substr($Haystack, 0, strlen($Needle)) == $Needle;
}
Snippet Details



$ExampleText = 'Hello world!';
 
if (StartsWith($ExampleText, 'Hello')){
    print 'The text starts with hello!';
}
 
 
$ExampleText = 'Evil monkey.';
 
if (!StartsWith($ExampleText, 'monkey')){
    print 'The text does not start with monkey!';
}

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

cyber June 16, 2011 at 16:50
hi
how i can greb html who contenet sarted whit any tag and ended any tag!
for example:
i want grab all content in this tag
<div class=it>
mnmnmnmfdgdsfgdfsg
dsfgdsfgdfsgfd
sgsfdgsdfg
dfgfdgdsfg
fdsgdsg
dfgsdfgsd
<div class=ip>
Jonas March 20, 2011 at 22:50
Hi kimi, just replace the "strpos" function of the first example with "stripos".
That should make the function case-insensitive.
kimi March 20, 2011 at 19:58
how to make function case-insensitive?
Christiaan August 30, 2009 at 13:22
the following should be even faster (when you have a lot of negative hits, ofc when its always positive its slower)

function startsWith($h, $n){
return (false !== ($i = strrpos($h, $n)) &&
$i === strlen($h) - strlen($n));
}
Andriy July 21, 2009 at 07:07
A bitty bit faster (by around 0.6%) version I use:

// Variables' ids shortened
function starts_with($h,$n) { // haystack, needle
return strpos($h,$n) === 0;
}
Andriy July 21, 2009 at 06:57
Hmmm. I tested this over and the newer version is indeed a bit more efficient for my needs (about 6.4% faster) than the older.

I wonder why...
Jonas September 25, 2007 at 18:19
Thanks for the notice, Eduard!

A year ago my programming skills were not the
best... Now I updated the snippet.

Jonas
Eduard Witteveen September 25, 2007 at 16:48
Isnt the following code sufficient?

function starts_with($str, $src){
return substr($src, 0, strlen($str))==$str;
}


Instead of: return true ? true : false;