PHP substr_count() 함수
예시
문자열에서 "world"가 나타나는 횟수를 계산합니다.
<?php
echo substr_count("Hello world. The world is nice","world");
?>
substr_count() 함수는 문자열에서 부분 문자열이 발생하는 횟수를 계산합니다.
참고: 하위 문자열은 대소문자를 구분합니다.
참고: 이 함수는 겹치는 부분 문자열을 계산하지 않습니다(예제 2 참조).
참고: 이 함수는 시작 매개변수에 길이 매개변수를 더한 값이 문자열 길이보다 큰 경우 경고를 생성합니다(예제 3 참조).
통사론
substr_count(string,substring,start,length)
매개변수 값
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
substring | Required. Specifies the string to search for |
start | Optional. Specifies where in string to start searching. If negative, it starts counting from the end of the string |
length | Optional. Specifies the length of the search |
기술적 세부 사항
반환 값: | 문자열에서 하위 문자열이 발생한 횟수를 반환합니다. |
---|---|
PHP 버전: | 4+ |
변경 로그: | PHP 7.1 - 길이 매개변수는 0 또는 음수일 수 있습니다. PHP 7.1 - 시작 매개변수는 음수일 수 있습니다. PHP 5.1 - 시작 및 길이 매개변수가 추가되었습니다. |
더 많은 예
예시
모든 매개변수 사용:
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
예시
겹친 부분 문자열:
<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
예시
시작 및 길이 매개변수가 문자열 길이를 초과하면 이 함수는 경고를 출력합니다.
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
길이 값이 문자열 길이를 초과하기 때문에 경고를 출력합니다(3+9는 12보다 큼).
❮ PHP 문자열 참조