函式名稱: str_word_count()
適用版本: PHP 4, PHP 5, PHP 7
函式描述: str_word_count() 函式計算字串中的單詞數。
用法: str_word_count(string $string, int $format = 0, string|null $charlist = null): mixed
引數:
- $string (必需): 要計算單詞數的字串。
- $format (可選): 指定返回值的格式。可選值為 0(預設)表示返回單詞數,1 表示返回單詞陣列,2 表示返回位置陣列。
- $charlist (可選): 指定要從字串中排除的字元列表。預設值為 null,表示不排除任何字元。
返回值:
- 當 $format 引數為 0 時,返回字串中的單詞數。
- 當 $format 引數為 1 時,返回一個包含字串中所有單詞的陣列。
- 當 $format 引數為 2 時,返回一個包含字串中所有單詞的位置陣列。
示例:
// 示例1: 返回字串中的單詞數
$string = "Hello world! This is a sample string.";
$wordCount = str_word_count($string);
echo $wordCount; // 輸出: 7
// 示例2: 返回一個包含字串中所有單詞的陣列
$string = "Hello world! This is a sample string.";
$wordArray = str_word_count($string, 1);
print_r($wordArray);
// 輸出:
// Array
// (
// [0] => Hello
// [1] => world
// [2] => This
// [3] => is
// [4] => a
// [5] => sample
// [6] => string
// )
// 示例3: 返回一個包含字串中所有單詞的位置陣列
$string = "Hello world! This is a sample string.";
$positionArray = str_word_count($string, 2);
print_r($positionArray);
// 輸出:
// Array
// (
// [0] => 0
// [6] => 6
// [12] => 12
// [16] => 16
// [19] => 19
// [21] => 21
// [28] => 28
// )
注意事項:
- 預設情況下,str_word_count() 函式使用空格字元作為單詞的分隔符,可以透過 $charlist 引數指定要排除的字元。
- $charlist 引數中的字元將被視為單詞分隔符,不會包含在返回的單詞中。
- 字串中的標點符號和特殊字元會被視為單詞的一部分。