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

來源:互聯網
上載者:User

執行個體

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

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

substr_count() Function Compute子串在字串中出現的次數。

注釋:子串是區分大小寫。

注釋:該函數不計數重疊的子串(參見執行個體 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 lengthecho substr_count($str,"is")."<br>"; // The number of times "is" occurs in the stringecho 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 參數超過字串長度,該函數則輸出一個警告:

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

由於長度值超過字串的長度(3 + 9大於12)。所以這將輸出一個警告。

舉例:

<?php$text = 'This is a test';echo strlen($text) . '<br />'; // 輸出14 echo substr_count($text, 'is') . '<br />'; // 2 // the string is reduced to 's is a test', so it prints 1echo substr_count($text, 'is', 3) . '<br />';//實際上就是從第四個字元開始尋找是否在$text中含有is // the text is reduced to 're ', so it prints 0echo substr_count($text, 'are', 16, 3) . '<br />'; // the text is reduced to 's i', so it prints 0echo substr_count($text, 'is', 3, 3); // generates a warning because 5+10 > 14echo substr_count($text, 'is', 5, 10) . '<br />';  // prints only 1, because it doesn't count overlapped subtrings$text2 = 'gcdgcdgcd';echo substr_count($text2, 'gcdgcd') . '<br />'; ?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.