Ends with

Returns true or fales depending on whether the text ends with the given string or not.

/**
 * EndsWith
 * Tests whether a text ends with the given
 * string or not.
 *
 * @param     string
 * @param     string
 * @return    bool
 */
function EndsWith($Haystack, $Needle){
    // Recommended version, using strpos
    return strrpos($Haystack, $Needle) === strlen($Haystack)-strlen($Needle);
}
 
// Another way, using substr
function EndsWith_Old($Haystack, $Needle){
    return substr($Haystack, strlen($Needle)*-1) == $Needle;
}
Snippet Details



$ExampleText = '[snippet]';
 
if (EndsWith($ExampleText, ']')){
    print 'The string ends with -> ] <-';
}
 
 
$ExampleText = 'Evil monkey';
 
if (!EndsWith($ExampleText, 'evil')){
    print 'The text does not start with evil!';
}

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:

jakob September 19, 2009 at 12:58
my proposal:
function endsWith($Haystack, $Needle){
return (substr($Haystack, strlen($Needle)*(-1)) == $Needle);
}
jakob September 19, 2009 at 12:55
Does not work for string, that have the same substring not only at the end. for example this returns false:
EndsWith('//TEST//', '//');
Christiaan August 30, 2009 at 13:24
The following should be a bit faster when you have a lot of negative hits (saves you 2x strlen() calls when not necessary).

function endsWith($h, $n){
return (false !== ($i = strrpos($h, $n)) &&
$i === strlen($h) - strlen($n));
}