>  기사  >  백엔드 개발  >  문자열에 하위 문자열이 나타나는 횟수를 계산하는 PHP 함수 substr_count()

문자열에 하위 문자열이 나타나는 횟수를 계산하는 PHP 함수 substr_count()

黄舟
黄舟원래의
2017-11-06 13:37:442058검색

"world"가 string에 나타나는 횟수 계산:

<?php
echo substr_count("Hello world. The world is nice","world");
?>

substr_count() 함수는 문자열에 하위 문자열이 나타나는 횟수를 셉니다.

참고: 하위 문자열은 대소문자를 구분합니다.

참고: 이 함수는 겹치는 부분 문자열을 계산하지 않습니다(예 2 참조).

참고: 시작 매개변수와 길이 매개변수를 더한 값이 문자열 길이보다 길면 이 함수는 경고를 생성합니다(예 3 참조).

Syntax

substr_count(string,substring,start,length)
Parameters Description
string 필수입니다. 확인할 문자열을 지정합니다.
substring 필수입니다. 검색할 문자열을 지정합니다.
시작 선택사항. 문자열에서 검색을 시작할 위치를 지정합니다.
길이 선택사항. 검색 길이를 지정합니다.

기술 세부 정보

반환 값: 문자열에 하위 문자열이 나타나는 횟수를 반환합니다.
PHP 버전: 4+
업데이트 로그: PHP 5.1에서는 시작 및 길이 매개변수가 추가.

更多实例

实例 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 PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>

实例 2

重叠的子串:

<?php
$str = "abcabcab"; 
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>

实例 3

如果 start 和 length 参数超过字符串长度,该函数则输出一个警告:

<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>

由于长度值超过字符串的长度(3 + 9大于12)。所以这将输出一个警告。

举例:

<?php
$text = &#39;This is a test&#39;;
echo strlen($text) . &#39;<br />&#39;; // 输出14
 
echo substr_count($text, &#39;is&#39;) . &#39;<br />&#39;; // 2
 
// the string is reduced to &#39;s is a test&#39;, so it prints 1
echo substr_count($text, &#39;is&#39;, 3) . &#39;<br />&#39;;//实际上就是从第四个字符开始查找是否在$text中含有is
 
// the text is reduced to &#39;re &#39;, so it prints 0
echo substr_count($text, &#39;are&#39;, 16, 3) . &#39;<br />&#39;;
 
// the text is reduced to &#39;s i&#39;, so it prints 0echo substr_count($text, &#39;is&#39;, 3, 3);
 
// generates a warning because 5+10 > 14
echo substr_count($text, &#39;is&#39;, 5, 10) . &#39;<br />&#39;;
 
 
// prints only 1, because it doesn&#39;t count overlapped subtrings
$text2 = &#39;gcdgcdgcd&#39;;
echo substr_count($text2, &#39;gcdgcd&#39;) . &#39;<br />&#39;;
 ?>

위 내용은 문자열에 하위 문자열이 나타나는 횟수를 계산하는 PHP 함수 substr_count()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.