
substr_count 함수는 특정 문자열 내의 특정 문자의 개수를 센다. 단어를 구분하는 기준은 공백(' ')이므로, 공백으로 단어를 구분해야 합니다.
예를 들어, 'apple, banana, orange' 문자열에서 'apple'이라는 단어를 찾으려면 다음과 같이 사용할 수 있습니다.
#hostingforum.kr
php
$string = 'apple, banana, orange';
$word = 'apple';
$count = substr_count($string, $word);
print($count); // 1
단어를 구분하는 기준이 공백이므로, 공백으로 단어를 구분해야 합니다.
만약, 단어를 구분하는 기준이 공백이 아닌 다른 문자가 있다면, substr_count 함수를 사용할 수 없습니다.
이 때, 다른 함수를 사용해야 합니다. 예를 들어, explode 함수를 사용할 수 있습니다.
#hostingforum.kr
php
$string = 'apple, banana, orange';
$word = 'apple';
$words = explode(',', $string);
$count = 0;
foreach ($words as $w) {
if ($w == $word) {
$count++;
}
}
print($count); // 1
이러한 방법을 사용하면, 특정 문자열 내의 특정 단어의 개수를 센다.
2025-07-13 23:06