php에서는 Java에서 처럼 startWith 이나 endWith 기능을 하는 함수가 없으므로 만들어서 써야한다. 다음과 같이 간단히 쓸 수 있다.



1. 함수



1
2
3
4
5
6
7
function startsWith($haystack, $needle){
    return strncmp($haystack, $needle, strlen($needle)) === 0;
}
 
function endsWith($haystack, $needle){
    return $needle === '' || substr_compare($haystack, $needle, -strlen($needle)) === 0;
}
cs



2. 결과


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


+ Recent posts