IT/PHP | CI

[PHP] 포함된 문자 찾기 str_contains(), str_starts_with(), str_ends_with() 및 strpos()

카제인나트륨. 2024. 6. 22. 18:35
728x90
반응형

PHP8 버전에서 추가된 몇가지 함수가 있습니다. 

그 중에서 특정 단어나 문자가 포함되어 있는 함수들을 소개해볼까 합니다.

1. str_contains()

  • 설명: 문자열이 특정 서브 문자열을 포함하는지 확인합니다.
  • 사용 예시
$string = "Hello, World!";
if (str_contains($string, "World")) {
    echo "Found!";
}
// 출력: Found!

## PHP8미만이라면 추가
if (!function_exists('str_contains')) {
    function str_contains($haystack = '', $needle = '') {
        return $needle !== '' && mb_strpos($haystack, $needle) !== false;
    }
}

2. str_starts_with()

  • 설명: 문자열이 특정 서브 문자열로 시작하는지 확인합니다.
  • 사용 예시
$string = "Hello, World!";
if (str_starts_with($string, "Hello")) {
    echo "Starts with Hello!";
}

## PHP8미만이라면 추가
if (!function_exists('str_starts_with')) {
    function str_starts_with($haystack, $needle) {
        return (string)$needle !== '' && strncmp($haystack, $needle, strlen($needle)) === 0;
    }
}

 

3. str_ends_with()

  • 설명: 문자열이 특정 서브 문자열로 끝나는지 확인합니다.
  • 사용 예시
$string = "Hello, World!";
if (str_ends_with($string, "World!")) {
    echo "Ends with World!";
}

## PHP8미만이라면 추가
if (!function_exists('str_ends_with')) {
    function str_ends_with($haystack, $needle) {
        return $needle !== '' && substr($haystack, -strlen($needle)) === (string)$needle;
    }
}

 

 

4. strpos

  • 설명: 특정 문자열이 처음으로 나타나는 위치를 찾습니다. 
  • 사용 예시
$haystack = "Hello, world!";
$needle = "world";
$pos = strpos($haystack, $needle);

if ($pos !== false) {
    echo "The string '$needle' was found in '$haystack' at position $pos";
} else {
    echo "The string '$needle' was not found in '$haystack'";
}

 

※ strpos()와 str_contains()함수의 차이점은 무엇인가?

 

  • 반환 값의 차이:
    • strpos(): 서브 문자열이 처음 나타나는 위치(인덱스)를 반환. 발견되지 않으면 false 반환.
    • str_contains(): 서브 문자열이 포함되어 있는지 여부를 true 또는 false로 반환.
  • 용도:
    • strpos(): 서브 문자열의 위치를 알아야 할 때 사용. 예를 들어, 문자열 내에서 서브 문자열이 처음 나타나는 위치를 기반으로 추가 작업을 수행할 때 유용.
    • str_contains(): 서브 문자열이 존재하는지 여부만 확인할 때 사용. 단순히 포함 여부만 필요할 때 코드가 더 간결해짐.
  • 가독성:
    • str_contains()는 포함 여부를 확인할 때 더 직관적이고 가독성이 좋습니다. strpos()를 사용할 때는 반환 값이 false인지, 위치가 0인지 구분해야 하는 경우가 있어 더 복잡할 수 있습니다.

 

개인적인 생각은 그러하나 판단은 본인 몫!

 

728x90
반응형