首頁  >  文章  >  後端開發  >  php計算子字串在字串中出現次數的函數substr_count()

php計算子字串在字串中出現次數的函數substr_count()

黄舟
黄舟原創
2017-11-06 13:37:442059瀏覽

實例

計算 "world" 在字串中出現的次數:

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

substr_count() 函數計算子字串在字串中出現的次數。

註解:子字串是區分大小寫的。

註解:此函數不計數重疊的子字串(請參閱實例 2) 。

註解:如果 start 參數加上 length 參數大於字串長度,函數則產生一個警告(請參閱實例 3)。

語法

substr_count(string,substring,start,length)
參數 #描述
string 必需。規定要檢查的字串。
substring 必要。規定要檢索的字串。
start 可選。規定在字串中何處開始搜尋。
length 可選。規定搜尋的長度。

技術細節

#返回值: #傳回子字串在字串中出現的次數。
PHP 版本: 4+
更新日誌 在PHP 5.1 中,新增了 start 和 length 參數。

更多实例

实例 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