PHP substr_count() 函數(shù)

2018-11-21 15:02 更新

PHP substr_count() 函數(shù)

PHP String 參考手冊(cè) PHP String 參考手冊(cè)

實(shí)例

計(jì)算 "world" 在字符串中出現(xiàn)的次數(shù):

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

運(yùn)行實(shí)例 ?

substr_count() 函數(shù)計(jì)算子串在字符串中出現(xiàn)的次數(shù)。

注釋:子串是區(qū)分大小寫的。

注釋:該函數(shù)不計(jì)數(shù)重疊的子串(參見實(shí)例 2) 。

注釋:如果 start 參數(shù)加上 length 參數(shù)大于字符串長(zhǎng)度,該函數(shù)則生成一個(gè)警告(參見實(shí)例 3)。


語(yǔ)法

substr_count(string,substring,start,length)

參數(shù) 描述
string 必需。規(guī)定要檢查的字符串。
substring 必需。規(guī)定要檢索的字符串。
start 可選。規(guī)定在字符串中何處開始搜索。
length 可選。規(guī)定搜索的長(zhǎng)度。

技術(shù)細(xì)節(jié)

返回值: 返回子串在字符串中出現(xiàn)的次數(shù)。
PHP 版本: 4+
更新日志: 在 PHP 5.1 中,新增了 startlength 參數(shù)。


更多實(shí)例

實(shí)例 1

使用所有的參數(shù):

<?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"
?>

運(yùn)行實(shí)例 ?

實(shí)例 2

重疊的子串:

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

運(yùn)行實(shí)例 ?

實(shí)例 3

如果 start 和 length 參數(shù)超過字符串長(zhǎng)度,該函數(shù)則輸出一個(gè)警告:

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

由于長(zhǎng)度值超過字符串的長(zhǎng)度(3 + 9大于12)。所以這將輸出一個(gè)警告。



PHP String 參考手冊(cè) PHP String 參考手冊(cè)
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)