2024 PHP Conference Japan

str_word_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

str_word_count 返回字串中使用的單詞資訊

說明

str_word_count(字串 $string, 整數 $format = 0, ?字串 $characters = null): 陣列|整數

計算 string 中的字數。如果未指定選用參數 format,則傳回值將是一個整數,表示找到的字數。如果指定了 format,則傳回值將是一個陣列,其內容取決於 formatformat 的可能值及其結果輸出如下所示。

在此函式中,「字詞」的定義為一個取決於地區設定的字串,包含字母字元,也可能包含但不以 "'" 和 "-" 字元開頭。請注意,不支援多位元組地區設定。

參數

string

要計算字數的字串

format

指定此函式的傳回值。目前支援的值為

  • 0 - 傳回找到的字數
  • 1 - 傳回一個陣列,包含在 string 中找到的所有字詞
  • 2 - 傳回一個關聯式陣列,其中鍵是字詞在 string 中的數字位置,值是實際的字詞本身

characters

額外字元列表,這些字元將被視為「字詞」的一部分

傳回值

根據所選的 format,傳回一個陣列或一個整數。

更新日誌

版本 說明
8.0.0 characters 現在可以為 null。

範例

範例 #1 str_word_count() 範例

<?php

$str
= "Hello fri3nd, you're
looking good today!"
;

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àáãç3'));

echo
str_word_count($str);

?>

以上範例將輸出

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)

Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7

參見

新增筆記

使用者貢獻的筆記 30 則筆記

cito at wikatu dot com
12 年前
<?php

/***
* 這個簡單的 utf-8 字數統計函式(它只計算數量)
* 比使用 preg_match_all 的函式快一點
* 比內建的 str_word_count 慢約 10 倍
*
* 如果您需要連字號或其他程式碼點作為單字字元
* 只需將它們放入 [括號] 中,例如 [^\p{L}\p{N}\'\-]
* 如果模式包含 utf-8,請使用 utf8_encode() 編碼模式,
* 因為預期它是有效的 utf-8(使用 u 修飾符)。
**/

// Jonny 5 的簡易單字分割器
function str_word_count_utf8($str) {
return
count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
?>
splogamurugan at gmail dot com
15 年前
我們也可以為 charlist 指定一個值的範圍。

<?php
$str
= "Hello fri3nd, you're
looking good today!
look1234ing"
;
print_r(str_word_count($str, 1, '0..3'));
?>

會得到以下結果

Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )
Adeel Khan
16 年前
<?php

/**
* 傳回字串中的字數。
* 根據我的測試,它非常準確。
* 字串可以包含 HTML,
* 但您應該先執行以下操作:
*
* $search = array(
* '@<script[^>]*?>.*?</script>@si',
* '@<style[^>]*?>.*?</style>@siU',
* '@<![\s\S]*?--[ \t\n\r]*>@'
* );
* $html = preg_replace($search, '', $html);
*
*/

function word_count($html) {

# 移除所有 HTML 標籤
$wc = strip_tags($html);

# 移除不包含字母數字字元或標點符號的「字詞」
$pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#";
$wc = trim(preg_replace($pattern, " ", $wc));

# 移除僅由標點符號組成的單字母「字詞」
$wc = trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#", " ", $wc));

# 移除多餘的空白
$wc = preg_replace("/\s\s+/", " ", $wc);

# 將字串分割成字詞陣列
$wc = explode(" ", $wc);

# 移除空元素
$wc = array_filter($wc);

# 傳回字數
return count($wc);

}

?>
MadCoder
19 年前
這是一個函式,它會將 $string 修剪到特定字數,並在其末尾加上...
(muz1 的前 100 個字程式碼的擴充)

----------------------------------------------
<?php
function trim_text($text, $count){
$text = str_replace(" ", " ", $text);
$string = explode(" ", $text);
for (
$wordCounter = 0; $wordCounter <= $count;$wordCounter++ ){
$trimed .= $string[$wordCounter];
if (
$wordCounter < $count ){ $trimed .= " "; }
else {
$trimed .= "..."; }
}
$trimed = trim($trimed);
return
$trimed;
}
?>

用法:
------------------------------------------------
<?php
$string
= "one two three four";
echo
trim_text($string, 3);
?>

回傳值:
one two three...
uri at speedy dot net
12 年前
這裡有一個支援 UTF-8 和希伯來文的字數計算函式。我嘗試了其他函式,但它們都無法正常運作。請注意,在希伯來文中,雙引號「"」和單引號「'」可以用在單字中,因此它們不是分隔符號。這個函式並不完美,我更喜歡我們在 JavaScript 中使用的一個函式,它將除了 [a-zA-Zא-ת0-9_\'\"] 之外的所有字元都視為分隔符號,但我不知道如何在 PHP 中做到這一點。

我移除了一些與希伯來文不相容的分隔符號 ("\x20", "\xA0", "\x0A", "\x0D", "\x09", "\x0B", "\x2E")。我也移除了底線。

這是對我之前在此頁面上發佈文章的修正——我發現我的函式在處理空字串時會返回不正確的結果。我已更正它,並且還附上另一個函式——my_strlen。

<?php

函式 count_words($string) {
// 回傳字串中的字數。
$string= str_replace("&#039;", "'", $string);
$t= 陣列(' ', "\t", '=', '+', '-', '*', '/', '\\', ',', '.', ';', ':', '[', ']', '{', '}', '(', ')', '<', '>', '&', '%', '$', '@', '#', '^', '!', '?', '~'); // 分隔符號
$string= str_replace($t, " ", $string);
$string= trim(preg_replace("/\s+/", " ", $string));
$num= 0;
如果 (
my_strlen($string)>0) {
$word_array= explode(" ", $string);
$num= count($word_array);
}
回傳
$num;
}

函式
my_strlen($s) {
// 以 UTF-8 編碼回傳 mb_strlen。
回傳 mb_strlen($s, "UTF-8");
}

?>
manrash at gmail dot com
15 年前
對於西班牙語使用者來說,一個有效的字元映射可能是

<?php
$characterMap
= 'áéíóúüñ';

$count = str_word_count($text, 0, $characterMap);
?>
brettNOSPAM at olwm dot NO_SPAM dot com
22 年前
這個例子可能不太美觀,但它證明是準確的。

<?php
//計算字數
$words_to_count = strip_tags($body);
$pattern = "/[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-\-|:|\&|@)]+/";
$words_to_count = preg_replace ($pattern, " ", $words_to_count);
$words_to_count = trim($words_to_count);
$total_words = count(explode(" ",$words_to_count));
?>

希望我沒有漏掉任何標點符號。;-)
brettz9 - see yahoo
14 年前
除非字元列表允許,否則單字也不能以連字號結尾⋯⋯
charliefrancis at gmail dot com
15 年前
嗨,這是我第一次在 PHP 手冊上發文,希望你們會喜歡我寫的這個小函式。

它會返回一個具有特定字元限制的字串,但仍保留完整的單字。
一旦找到足夠短的字串顯示,它就會跳出 foreach 迴圈,並且可以編輯字元列表。

<?php
函數 word_limiter( $text, $limit = 30, $chars = '0123456789' ) {
如果(
strlen( $text ) > $limit ) {
$words = str_word_count( $text, 2, $chars );
$words = array_reverse( $words, TRUE );
foreach(
$words as $length => $word ) {
如果(
$length + strlen( $word ) >= $limit ) {
array_shift( $words );
} else {
break;
}
}
$words = array_reverse( $words );
$text = implode( " ", $words ) . '&hellip;';
}
返回
$text;
}

$str = "Hello this is a list of words that is too long";
echo
'1: ' . word_limiter( $str );
$str = "Hello this is a list of words";
echo
'2: ' . word_limiter( $str );
?>

1: Hello this is a list of words&hellip;
2: Hello this is a list of words
匿名
19 年前
這個函數似乎將數字視為空白。也就是說,僅由數字組成的單詞不會被計算在內。
php dot net at salagir dot com
6 年前
即使在帶有重音符號的地區設定中,這個函數也無法處理重音符號。
<?php
echo str_word_count("Is working"); // =2

setlocale(LC_ALL, 'fr_FR.utf8');
echo
str_word_count("Not wôrking"); // 預期為 2,結果為 3。
?>

Cito 的解決方案將標點符號視為單詞,因此並不是一個好的解決方法。
<?php
函數 str_word_count_utf8($str) {
返回
count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
echo
str_word_count_utf8("Is wôrking"); //=2
echo str_word_count_utf8("Not wôrking."); //=3
?>

我的解決方案
<?php
函式 str_word_count_utf8($str) {
$a = preg_split('/\W+/u', $str, -1, PREG_SPLIT_NO_EMPTY);
返回
count($a);
}
echo
str_word_count_utf8("Is wôrking"); // = 2
echo str_word_count_utf8("Is wôrking! :)"); // = 2
?>
dmVuY2lAc3RyYWhvdG5pLmNvbQ== (base64)
14 年前
要計算使用 antiword 將 MS Word 文件轉換為純文字後的字數,您可以使用這個函式

<?php
函式 count_words($text) {
$text = str_replace(str_split(|'), '', $text); // 移除這些字元 (您可以指定更多)
$text = trim(preg_replace('/\s+/', ' ', $text)); // 移除多餘的空格
$text = preg_replace('/-{2,}/', '', $text); // 移除連續兩個或多個破折號
$len = strlen($text);

if (
0 === $len) {
返回
0;
}

$words = 1;

while (
$len--) {
if (
' ' === $text[$len]) {
++
$words;
}
}

返回
$words;
}
?>

它會去除 antiword 用於在其純文字輸出中格式化表格的 "|" 字元,移除連續多個破折號(也用於表格中),然後計算字數。

使用 explode() 然後 count() 來計算字數對於大量文字來說並不是一個好主意,因為它會使用大量記憶體將文字再次儲存為陣列。這就是為什麼我使用 while() { .. } 來遍歷字串的原因
rcATinterfacesDOTfr
21 年前
這是另一種計算字數的方法
$word_count = count(preg_split('/\W+/', $text, -1, PREG_SPLIT_NO_EMPTY));
jazz090
15 年前
就我個人而言,我不喜歡使用這個函式,因為它省略的字元有時是必要的,例如 MS Word 將 ">" 或 "<" 單獨算作一個字,而這個函式則不會。然而,我喜歡使用這個方法,它會計算所有的東西

<?php
函數 num_words($string){
preg_match_all("/\S+/", $string, $matches);
返回
count($matches[0]);
}
?>
joshua dot blake at gmail dot com
17 年前
我需要一個函數,可以從給定的輸入中提取前一百個單詞,同時保留所有標記,例如換行符、雙倍空格等。上面發佈的大多數基於正規表達式的函數在計算一百個單詞方面是準確的,但是通過將陣列壓縮成字串來重新組合段落。這消除了任何保留換行符號的希望,因此我設計了一個粗糙但非常準確的函數,它可以滿足我的所有要求。

<?php
函數 Truncate($input, $numWords)
{
如果(
str_word_count($input,0)>$numWords)
{
$WordKey = str_word_count($input,1);
$PosKey = str_word_count($input,2);
reset($PosKey);
對每個(
$WordKey 作為 $key => &$value)
{
$value=key($PosKey);
next($PosKey);
}
返回
substr($input,0,$WordKey[$numWords]);
}
否則 {返回
$input;}
}
?>

它背後的想法?遍歷 str_word_count 返回的陣列的鍵,並將每個單詞的編號与其在片語中的字元位置關聯起來。然後使用 substr 返回直到第 n 個字元的所有內容。我在相當大的條目上測試了這個函數,它似乎足夠有效,完全不會造成系統負擔。

加油!

Josh
josh at joshblake.net
17 年前
我對一個能從較長字串中返回前幾個單詞的函數很感興趣。

實際上,我想要預覽一篇遠超過一百字的部落格文章的前一百個單詞。

我發現所有其他將字串分解並合併成陣列的函數都會遺失關鍵標記,例如換行符號等。

所以,這就是我想出的辦法

<?php
function WordTruncate($input, $numWords) {
if(
str_word_count($input,0)>$numWords)
{
$WordKey = str_word_count($input,1);
$WordIndex = array_flip(str_word_count($input,2));
return
substr($input,0,$WordIndex[$WordKey[$numWords]]);
}
else {return
$input;}
}
?>

雖然我沒有逐一計算,但這對我的需求來說已經夠準確了。如果字數少於指定的數量,它也會返回整個字串。

背後的原理?使用 `str_word_count` 找出第 n 個字,然後再次使用 `str_word_count` 找出該字在字串中的位置,最後使用 `substr` 擷取到該位置為止的子字串。

Josh.
Samer Ata
12 年前
這是我自己寫的版本,用於從 WordPress 文章內容中取得 SEO meta description。它也可以作為通用函式,用於取得字串中的前 n 個字。

<?php
function my_meta_description($text,$n=10)
{
$text=strip_tags($text); // 非 HTML 的情況下並非必要
// $text=strip_shortcodes($text); // 僅在 WordPress 系統內取消註解
$text = trim(preg_replace("/\s+/"," ",$text));
$word_array = explode(" ", $text);
if (
count($word_array) <= $n)
return
implode(" ",$word_array);
else
{
$text='';
foreach (
$word_array as $length=>$word)
{
$text.=$word ;
if(
$length==$n) break;
else
$text.=" ";
}
}
return
$text;
?>
philip at cornado dot com
21 年前
有些人問到不只是用空格來分割,這是因為僅僅使用空格分割並不夠精確。單詞之間可能用 tab、換行、雙倍空格等分隔。這就是為什麼人們傾向於使用正規表達式來根據所有空白字元進行分割。
aix at lux dot ee
20 年前
一個函式。
<?php
if (!function_exists('word_count')) {
function
word_count($str,$n = "0"){
$m=strlen($str)/2;
$a=1;
while (
$a<$m) {
$str=str_replace(" "," ",$str);
$a++;
}
$b = explode(" ", $str);
$i = 0;
foreach (
$b as $v) {
$i++;
}
if (
$n==1) return $b;
else return
$i;

}
}
$str="Tere Tartu linn";
$c = word_count($str,1); // 傳回一個陣列
$d = word_count($str); // 傳回整數 - 文本中的字數
print_r($c);
echo
$d;
?>
匿名
17 年前
這裡有一個 PHP 字數統計函式,以及一個 JavaScript 版本,它們會印出相同的結果。

<?php
// PHP 字數統計函式
function word_count($theString)
{
$char_count = strlen($theString);
$fullStr = $theString . " ";
$initial_whitespace_rExp = "^[[:alnum:]]$";

// 注意:ereg_replace 已過時,建議使用 preg_replace
$left_trimmedStr = preg_replace('/' . $initial_whitespace_rExp . '/',"",$fullStr);
$non_alphanumerics_rExp = "^[[:alnum:]]$";
// 注意:ereg_replace 已過時,建議使用 preg_replace
$cleanedStr = preg_replace('/' . $non_alphanumerics_rExp . '/'," ",$left_trimmedStr);
$splitString = explode(" ",$cleanedStr);

$word_count = count($splitString) - 1;

if (
strlen($fullStr) < 2)
{
$word_count = 0;
}
return
$word_count;
}
?>

<?php
//計算片語中單字數量的函式
function wordCount(theString)
{
var
char_count = theString.length;
var
fullStr = theString + " ";
var
initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var
left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var
non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var
cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var
splitString = cleanedStr.split(" ");

var
word_count = splitString.length -1;

if (
fullStr.length <2)
{
word_count = 0;
}
return
word_count;
}
?>
Kirils Solovjovs
20 年前
這個方法對我來說完全沒用。我認為 countwords() 函式非常依賴編碼。這段程式碼適用於 win1257 編碼。若要使用其他編碼,只需要重新定義字母的範圍即可…

<?php
function countwords($text){
$ls=0;//判斷是否為空白
$cc33=0;//計數器
for($i=0;$i<strlen($text);$i++){
$spstat=false; //判斷是否為數字或字母
$ot=ord($text[$i]);
if( ((
$ot>=48) && ($ot<=57)) || (($ot>=97) && ($ot<=122)) || (($ot>=65) && ($ot<=90)) || ($ot==170) ||
((
$ot>=192) && ($ot<=214)) || (($ot>=216) && ($ot<=246)) || (($ot>=248) && ($ot<=254)) )$spstat=true;
if((
$ls==0)&&($spstat)){
$ls=1;
$cc33++;
}
if(!
$spstat)$ls=0;
}
return
$cc33;
}

?>
broncha at rajesharma dot com
9 年前
結果發現網頁預設的字元列表已設定。例如,字串

Copyright &copy; ABC Ltd.

在命令列介面中是 3 個字,但在網頁環境中執行則是 4 個字。
Artimis
21 年前
絕對不要使用這個函式來計算/分隔字母數字組成的單字,它只會將單字拆成單個字元,數字拆成單個數字。在分隔字母數字組成的單字時,您可以參考另一個函式 "preg_split"。它也適用於中文字元。
matthewkastor at live dot com
13 年前
這個函式需要改進,但目前運作良好。

<?php
/**
* Generates an alphabetical index of unique words, and a count of their occurrences, in a file.
*
* This works on html pages or plain text files.
* This function uses file_get_contents, so it
* is possible to use a url instead of a local filename.
*
* Change the search pattern at
* <code> $junk = preg_match('/[^a-zA-Z]/', $word); </code>
* if you want to keep words with numbers or other characters. The pattern
* I've set searches for anything that is not an upper or lowercase letter,
* you may want something else.
*
* The array returned will look something like this:
* <code>
* Array
* (
* [0] => Array
* (
* [word] => a
* [count] => 21
* )
*
* [1] => Array
* (
* [word] => ability
* [count] => 1
* )
* )
* </code>
*
* @param string $file The file ( or url ) you want to create an index from.
* @return array
*/
function index_page($file) {
$index = array();
$find = array(
'/\r/',
'/\n/',
'/\s\s+/'
);
$replace = array(
' ',
' ',
' '
);
$work = file_get_contents($file);
$work = preg_replace('/[>][<]/', '> <', $work);
$work = strip_tags($work);
$work = strtolower($work);
$work = preg_replace($find, $replace, $work);
$work = trim($work);
$work = explode(' ', $work);
natcasesort($work);
$i = 0;
foreach(
$work as $word) {
$word = trim($word);
$junk = preg_match('/[^a-zA-Z]/', $word);
if(
$junk == 1) {
$word = '';
}
if( (!empty(
$word)) && ($word != '') ) {
if(!isset(
$index[$i]['word'])) { // if not set this is a new index
$index[$i]['word'] = $word;
$index[$i]['count'] = 1;
} elseif(
$index[$i]['word'] == $word ) { // count repeats
$index[$i]['count'] += 1;
} else {
// else this is a different word, increment $i and create an entry
$i++;
$index[$i]['word'] = $word;
$index[$i]['count'] = 1;
}
}
}
unset(
$work);
return(
$index);
}
?>

使用範例

<?php
$file
= 'https://php.dev.org.tw/';
// 或使用本地檔案,請參閱 file_get_contents() 以了解有效的檔案名稱和限制。

$index = index_page($file);
echo
'<pre>'.print_r($index,true).'</pre>';
?>
lwright at psu dot edu
18 年前
如果您要計算單字出現的頻率,請嘗試

<?php

$wordfrequency
= array_count_values( str_word_count( $string, 1) );

?>
andrea at 3site dot it
21 年前
如果字串不包含空格「 」,explode 方法將不會執行任何操作,所以我寫了這個,它似乎運作得更好...我不確定時間和資源的使用情況

<?php
function str_incounter($match,$string) {
$count_match = 0;
for(
$i=0;$i<strlen($string);$i++) {
if(
strtolower(substr($string,$i,strlen($match)))==strtolower($match)) {
$count_match++;
}
}
return
$count_match;
}
?>

範例

<?php
$string
= "something:something!!something";
$count_some = str_incounter("something",$string);
// 將會回傳 3
?>
eanimator at yahoo dot com
15 年前
我的快速且粗略的 wordLimiter 函式。

<?php
function WordLimiter($text,$limit=20){
$explode = explode(' ',$text);
$string = '';

$dots = '...';
if(
count($explode) <= $limit){
$dots = '';
}
for(
$i=0;$i<$limit;$i++){
$string .= $explode[$i]." ";
}

return
$string.$dots;
}
?>
amosbatto at yahoo dot com
3 年前
// 為了準確計算英文單字數量,某些包含特殊發音符號的單字,
// 例如 née、Chloë、naïve、coöpt、façade、piñata 等,需要加入對應的發音符號。
$count = str_word_count($str, 0, 'éëïöçñÉËÏÖÇÑ');

// 計算任何使用羅馬字母的歐洲語言之單字數量
$count = str_word_count($str, 0, 'äëïöüÄËÏÖÜáǽćéíĺńóŕśúźÁǼĆÉÍĹŃÓŔŚÚŹ'.
'àèìòùÀÈÌÒÙãẽĩõñũÃẼĨÕÑŨâêîôûÂÊÎÔÛăĕğĭŏœ̆ŭĂĔĞĬŎŒ̆Ŭ'.
'āēīōūĀĒĪŌŪőűŐŰąęįųĄĘĮŲåůÅŮæÆøØýÝÿŸþÞẞßđĐıIœŒ'.
'čďěľňřšťžČĎĚĽŇŘŠŤŽƒƑðÐłŁçģķļșțÇĢĶĻȘȚħĦċėġżĊĖĠŻʒƷǯǮŋŊŧŦ');
dev dot vegera at gmail dot com
4 年前
基於 preg_match_all 的函式,用以模仿 str_word_count 的行為

<?php
function mb_str_word_count($str, $format = 2, $charlist = '') {
if (
$format < 0 || $format > 2) {
throw new
InvalidArgumentException('參數 #2 ($format) 必須是有效的格式值');
}
$count = preg_match_all('#[\p{L}\p{N}][\p{L}\p{N}\'' . $charlist . ']*#u', $str, $matches, $format === 2 ? PREG_OFFSET_CAPTURE : PREG_PATTERN_ORDER);
if (
$format === 0) {
return
$count;
}
$matches = $matches[0] ?? [];
if (
$format === 2) {
$result = [];
foreach (
$matches as $match) {
$result[$match[1]] = $match[0];
}
return
$result;
}
return
$matches;
}
?>
aidan at php dot net
20 年前
此功能現在已在 PEAR 套件 PHP_Compat 中實現。

更多關於如何在不升級 PHP 版本的情況下使用此功能的資訊,請參考以下連結

http://pear.php.net/package/PHP_Compat
To Top