PHP startsWith and endsWith

function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
function endsWith($haystack, $needle) {
    // search forward starting from end minus needle length characters
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
}
startsWith("abcdef", "ab") -> true
startsWith("abcdef", "cd") -> false
startsWith("abcdef", "ef") -> false
startsWith("abcdef", "") -> true
startsWith("", "abcdef") -> false

endsWith("abcdef", "ab") -> false
endsWith("abcdef", "cd") -> false
endsWith("abcdef", "ef") -> true
endsWith("abcdef", "") -> true
endsWith("", "abcdef") -> false

 


Source page: http://stackoverflow.com/a/10473026

posted @ 2015-12-26 16:26  Waichung  阅读(1244)  评论(0编辑  收藏  举报