PHP에서 문자열 안에 특정 부분 문자열(하위 문자열)이 포함되어 있는지 확인하려면 strpos() 함수를 사용할 수 있습니다. 이 함수는 부분 문자열이 처음 나타나는 위치(인덱스)를 반환하고, 찾지 못하면 false를 반환합니다.
예제 1: 부분 문자열이 존재하는 경우
<?php
$subStr = "Mother";
$str = "How I Met Your Mother";
echo "String = $str";
echo "\nSubstring = $subStr";
if(strpos($str, $subStr) !== false){
echo "\nSubstring found successfully";
} else{
echo "\nSubstring not found";
}
?>출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
String = How I Met Your Mother Substring = Mother Substring found successfully
원본 문자열 "How I Met Your Mother"에는 "Mother"라는 부분 문자열이 존재하므로 "Substring found successfully"가 출력됩니다.
예제 2: 부분 문자열이 존재하지 않는 경우
이번에는 부분 문자열이 없는 경우의 예제를 살펴보겠습니다.
<?php
$subStr = "Ocean";
$str = "In the Heart of Sea";
echo "String = $str";
echo "\nSubstring = $subStr";
if(strpos($str, $subStr) !== false){
echo "\nSubstring found successfully";
} else{
echo "\nSubstring not found";
}
?>출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
String = In the Heart of Sea Substring = Ocean Substring not found
"In the Heart of Sea" 문자열에는 "Ocean"이라는 단어가 포함되어 있지 않으므로 "Substring not found"가 출력됩니다.
주의 사항: 엄격한 비교(!==)를 사용해야 하는 이유
strpos() 함수의 반환값을 비교할 때는 반드시 !== false처럼 엄격한 비교(strict comparison)를 사용해야 합니다. 만약 == 또는 !=로 느슨하게 비교하면, 부분 문자열이 문자열의 맨 앞(인덱스 0)에 위치할 때 반환값 0이 false로 취급되어 존재함에도 불구하고 "찾지 못했다"는 잘못된 결과가 나올 수 있습니다.