Tuesday, 23 January 2018

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;
}

$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!';
}

0 comments:

Post a Comment