Computer >> 컴퓨터 >  >> 프로그래밍 >> PHP

PHP 8의 str_starts_with()와 str_ends_with() 함수 완벽 정리

PHP 8에서 새롭게 추가된 str_starts_with()str_ends_with() 함수는 주어진 문자열이 특정 문자열로 시작하거나 끝나는지 여부를 간편하게 확인할 수 있는 내장 함수입니다. 조건이 일치하면 true, 일치하지 않으면 false를 반환합니다.

기본 사용 예제

str_starts_with('hello haystack', 'hello'); // 'hello'로 시작함 → true
str_ends_with('hello haystack', 'stack');   // 'stack'으로 끝남 → true

str_starts_with('hello haystack', 'hay');   // 'hello'로 시작하지 않음 → false
str_ends_with('hello haystack', 'hay');     // 'stack'으로 끝나지 않음 → false

두 함수 모두 대소문자를 구분하며, PHP 8 이전에는 substr()이나 strpos() 등을 조합해야 했던 문자열 접두사·접미사 검사를 훨씬 직관적이고 가독성 좋게 처리할 수 있습니다.

str_starts_with() 함수

이 함수는 주어진 문자열($haystack)이 지정한 문자열($needle)로 시작하는지 검사합니다. 시작 부분에서 해당 문자열을 찾으면 true, 찾지 못하면 false를 반환합니다.

str_starts_with(string $haystack, string $needle): bool

예제 : str_starts_with() 함수 활용

<?php
    if (str_starts_with('hellohaystack', "hello")) {
        echo "string starts with hello";
    }
?>

출력 결과

String starts with 'hello'

참고: 두 번째 인자로 전달한 문자열이 첫 번째 문자열의 시작 부분에서 발견되지 않으면 false를 반환합니다.

str_ends_with() 함수

이 함수는 주어진 문자열($haystack)이 지정한 문자열($needle)로 끝나는지 검사합니다. 끝 부분에서 해당 문자열을 찾으면 true, 찾지 못하면 false를 반환합니다.

str_ends_with(string $haystack, string $needle): bool

예제 : str_ends_with() 함수 활용

<?php
    if (str_ends_with('hellohaystack', "stack")) {
        echo "string ends with stack";
    }
?>

출력 결과

String ends with 'stack'