str_word_count()函數是PHP中的內置函數,用於返回有關字符串中使用的單詞的信息,例如字符串中的總數單詞,字符串中單詞的位置等。
用法:
str_word_count ( $string , $returnVal, $chars )
使用的參數:
- $string:此參數指定用戶要計數其單詞的字符串。這不是可選參數。
-
$returnVal:str_word_count()函數的返回值由$returnVal參數指定。它是一個可選參數,默認值為0。
該參數可以根據需要采用以下值:- 0:它返回字符串$string中的單詞數。
- 1:它返回一個包含所有在字符串中找到的單詞的數組。
- 2:它返回具有鍵值對的關聯數組,其中鍵定義單詞在字符串中的位置,而值是單詞本身。
- $chars:這是一個可選參數,用於指定其他字符列表,這些字符應被視為“單詞”。
返回類型:函數的返回類型取決於參數$returnVal並返回如上所述的值。
下麵的程序解釋了str_word_count()函數的工作:
-
計算字符串中的單詞數:要僅顯示字符串中的單詞數,應按以下方式執行str_word_count()函數:
<?php $mystring = "Twinkle twinkl4e little star"; print_r(str_word_count($mystring)); ?>
輸出:
5
-
查找字符串中的單詞:要返回包含字符串中的單詞的數組,應按以下方式執行str_word_count()函數:
<?php $mystring = "Twinkle twinkl4e little star"; print_r(str_word_count($mystring, 1)); ?>
輸出:
Array ( [0] => Twinkle [1] => twinkl [2] => e [3] => little [4] => star )
-
查找字符串中的單詞以及單詞的數字位置:要返回包含字符串中的單詞以及單詞的數字位置的數組,則應按以下方式執行str_word_count()函數:
<?php $mystring = "Twinkle twinkl4e little star"; print_r(str_word_count($mystring, 2)); ?>
輸出:
Array ( [0] => Twinkle [8] => twinkl [15] => e [17] => little [24] => star )
-
當某些特殊字符被視為單詞時,在字符串中查找單詞:要返回包含字符串中的單詞的數組,其中應將一個字符視為一個單詞,則應按以下方式執行str_word_count()函數:
<?php $mystring = "Twinkle twinkl4e little star"; print_r(str_word_count($mystring, 2 ,4)); ?>
輸出:
Array ( [0] => Twinkle [8] => twinkl4e [17] => little [24] => star )
相關用法
- p5.js nfc()用法及代碼示例
- p5.js nfp()用法及代碼示例
- d3.js d3.hcl()用法及代碼示例
- p5.js nfs()用法及代碼示例
- PHP cos( )用法及代碼示例
- PHP sin( )用法及代碼示例
- p5.js nf()用法及代碼示例
- PHP tan( )用法及代碼示例
- PHP pow( )用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- d3.js d3.set.has()用法及代碼示例
- PHP Ds\Set xor()用法及代碼示例
注:本文由純淨天空篩選整理自Shubrodeep Banerjee大神的英文原創作品 PHP | str_word_count() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。