str_word_count

(PHP 4 >= 4.3.0, PHP 5)

str_word_count Возвращает информацию о словах, входящих в строку

Описание

mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )

Подсчитывает количество слов, входящих в строку string. Если необязательный аргумент format не передан, возвращается целое число, равное количеству слов. В случае, если указан аргумент format, возвращается массив, содержимое которого зависит от значения format. Ниже описаны допустимые значения аргумента format и соответствующие им возвращаемые значения.

Для этой функции "слово" обозначает строку с алфавитными символами, зависящую от локали, которая также может содержать символы "'" и "-", но не может начинаться с них.

Список параметров

string

Строка

format

Указывает возвращаемое значение данной функции. На данный момент поддерживаются следующие значения:

  • 0 - возвращает количество найденных слов
  • 1 - возвращается массив, содержащий все слова, входящие в строку string
  • 2 - возвращается массив, индексами которого являются позиции в строке string, а значениями - соответствующие слова.

charlist

Список дополнительных символов, которые будут рассматриваться как "слово"

Возвращаемые значения

Возвращает массив или целое число, в зависимости от указанного параметра format.

Список изменений

Версия Описание
5.1.0 Добавлен параметр charlist

Примеры

Пример #1 Пример использования str_word_count()

<?php

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

print_r(str_word_count($str1));
print_r(str_word_count($str2));
print_r(str_word_count($str1'àáãç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

Смотрите также

  • explode() - Разбивает строку с помощью разделителя
  • preg_split() - Разбивает строку по регулярному выражению
  • split() - Разбиение строки на массив по регулярному выражению
  • count_chars() - Возвращает информацию о символах, входящих в строку
  • substr_count() - Возвращает число вхождений подстроки

Коментарии

i tried to write a wordcounter and ended up with this:

<?php
//strip html-codes or entities
$text strip_tags(strtr($textarray_flip(get_html_translation_table(HTML_ENTITIES))));
//count the words
$wordcount preg_match_all("#(\w+)#"$text$match_dummy );
?>
2002-10-31 16:48:39
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This example may not be pretty, but It proves accurate:

<?php
//count words
$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));
?>

Hope I didn't miss any punctuation. ;-)
2002-11-09 14:06:14
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Here is another way to count words :
$word_count = count(preg_split('/\W+/', $text, -1, PREG_SPLIT_NO_EMPTY));
2003-01-16 09:58:14
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Some ask not just split on ' ', well, it's because simply exploding on a ' ' isn't fully accurate.  Words can be separated by tabs, newlines, double spaces, etc.  This is why people tend to seperate on all whitespace with regular expressions.
2003-04-06 22:30:38
http://php5.kiev.ua/manual/ru/function.str-word-count.html
I will not discuss the accuracy of this function but one of the source codes above does this.

<?php
function wrdcnt($haystack) {
 
$cnt explode(" "$haystack);
 return 
count($cnt) - 1;
}
?>

That could be replace by 

<?php
function wrdcnt($haystack) {
 return 
substr_count($haystack,' ') + 1;
}
?>

I doubt this does need to be a function :)
2003-04-11 09:10:44
http://php5.kiev.ua/manual/ru/function.str-word-count.html
[Ed: You'd probably want to use regular expressions if this was the case --alindeman @ php.net]

Consider what will happen in some of the above suggestions when a person puts more than one space between words. That's why it's not sufficient just to explode the string.
2003-04-18 21:29:58
http://php5.kiev.ua/manual/ru/function.str-word-count.html
if string doesn't contain the space " ", the explode method doesn't do anything, so i've wrote this and it seems works better ... i don't know about time and resource

<?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;
}
?>

example 

<?php
$string 
"something:something!!something";
$count_some str_incounter("something",$string);
// will return 3
?>
2003-05-19 07:55:44
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
Never use this function to count/separate alphanumeric words, it will just split them up words to words, numbers to numbers.  You could refer to another function "preg_split" when splitting alphanumeric words.  It works with Chinese characters as well.
2003-10-15 05:32:06
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
Nothing of this worked for me. I think countwords() is very encoding dependent. This is the code for win1257. For other layots you just need to redefine the ranges of letters...

<?php
function countwords($text){
       
$ls=0;//was it a whitespace?
       
$cc33=0;//counter
       
for($i=0;$i<strlen($text);$i++){
               
$spstat=false//is it a number or a letter?
               
$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;
}

?>
2004-02-22 11:06:07
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
2004-06-26 06:02:18
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
One function.
<?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); // it return an array
$d  word_count($str); // it return int - how many words was in text
print_r($c);
echo 
$d;
?>
2004-11-14 04:53:37
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
This function seems to view numbers as whitespace. I.e. a word consisting of numbers only won't be counted.
2005-01-16 08:38:59
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This function is awesome however I needed to display the first 100 words of a string. I am submitting this as a possible solution but also to get feedback as to whether it is the most efficient way of doing it.

<?
                                    $currString 
explode(" "$string);
for (
$wordCounter=0$wordCounter<100$wordCounter++) { echo $currString[$wordCounter]." "; }
?>
2005-08-12 03:56:04
http://php5.kiev.ua/manual/ru/function.str-word-count.html
In reply to muz1's post below:

You can also take advantage of using other built in PHP functions to get to your final result.  Consider the following:
<?php
$string 
"One two three four five six seven eight nine ten.";
// the first n words to extract
$n 3;
// extract the words
$words explode(" "$string);
// chop the words array down to the first n elements
$firstN array_slice($words0$n);
// glue the 3 elements back into a spaced sentence
$firstNAsAString implode(" "$firstN);
// display it
echo $firstNAsAString;
?>

Or to do it all in one line:
<?php
echo implode(" "array_slice(explode(" "$string), 0$n));
?>
2005-08-14 10:59:52
http://php5.kiev.ua/manual/ru/function.str-word-count.html
In the previous note, the example will only extract from the string, words separated by exactly one space.  To properly extract words from all strings, use regular expressions.

Example (extracting the first 4 words):
<?php
$string 
"One    two three       four  five six";
echo 
implode(" "array_slice(preg_split("/\s+/"$string), 04));
?>

The above $string would not have otherwise worked when using the explode() method below.
2005-08-14 19:21:35
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
Here's a function that will trim a $string down to a certian number of words, and add a...   on the end of it.
(explansion of muz1's 1st 100 words code)

----------------------------------------------
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;
}

Usage
------------------------------------------------
$string = "one two three four";
echo trim_text($string, 3);

returns:
one two three...
2005-08-16 00:12:56
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Trying to make an effiecient word splitter, and "paragraph limiter", eg, limit item text to 100, or 200 words and so-forth.

I don't know how well this compares, but it works nicely.

function trim_text($string, $word_count=100)
{
    $trimmed = "";
    $string = preg_replace("/\040+/"," ", trim($string));
    $stringc = explode(" ",$string);
    echo sizeof($stringc);
    if($word_count >= sizeof($stringc))
    {
        // nothing to do, our string is smaller than the limit.
      return $string;
    }
    elseif($word_count < sizeof($stringc))
    {
        // trim the string to the word count
        for($i=0;$i<$word_count;$i++)
        {
            $trimmed .= $stringc[$i]." ";
        }
       
        if(substr($trimmed, strlen(trim($trimmed))-1, 1) == '.')
          return trim($trimmed).'..';
        else
          return trim($trimmed).'...';
    }
}

$text = "some  test          text goes in here, I'm not sure, but ok.";
echo trim_text($text,5);
2005-09-25 19:58:57
http://php5.kiev.ua/manual/ru/function.str-word-count.html
There is a small bug in the "trim_text" function by "webmaster at joshstmarie dot com" below. If the string's word count is lesser than or equal to $truncation, that function will cut off the last word in the string.

[EDITOR'S NOTE: above referenced note has been removed]

This fixes the problem:

<?php
function trim_text_fixed($string$truncation 250) {
   
$matches preg_split("/\s+/"$string$truncation 1);
   
$sz count($matches);
    if ( 
$sz $truncation ) {
        unset(
$matches[$sz-1]);
        return 
implode(' ',$matches);
    }
    return 
$string;
}
?>
2006-04-05 02:03:18
http://php5.kiev.ua/manual/ru/function.str-word-count.html
If you are looking to count the frequency of words, try:

<?php

$wordfrequency 
array_count_valuesstr_word_count$string1) );

?>
2006-08-17 14:51:25
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
I found a more reliable way to print, say the first 100 words and then print elipses. My code goes this way;

$threshold_length = 80; // 80 words max
$phrase = "...."; // populate this with the text you want to display
$abody = str_word_count($phrase,2);
if(count($abody) >= $threshold_length){ // gotta cut
  $tbody = array_keys($abody);
  echo "<p>" . substr($phrase,0,$tbody[$threshold_length]) . "... <span class=\"more\"><a href=\"?\">read more</a></span> </p>\n";
} else { // put the whole thing
  echo "<p>" . $phrase . "</p>\n";
}

For any questions, com.iname@artaxerxes2
2006-10-06 12:06:01
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
Here is a php work counting function together with a javascript version which will print the same result.

<?php
     
//Php word counting function
     
function word_count($theString)
      {
       
$char_count strlen($theString);
       
$fullStr $theString." ";
       
$initial_whitespace_rExp "^[[:alnum:]]$";
       
       
$left_trimmedStr ereg_replace($initial_whitespace_rExp,"",$fullStr);
       
$non_alphanumerics_rExp "^[[:alnum:]]$";
       
$cleanedStr ereg_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 to count words in a phrase
     
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;
      }
?>
2007-01-30 10:15:01
http://php5.kiev.ua/manual/ru/function.str-word-count.html
I was interested in a function which returned the first few words out of a larger string.

In reality, I wanted a preview of the first hundred words of a blog entry which was well over that.

I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc.

So, this is what I came up with:

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;}
}

While I haven't counted per se, it's accurate enough for my needs. It will also return the entire string if it's less than the specified number of words.

The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position.

Josh.
2007-03-01 17:57:25
http://php5.kiev.ua/manual/ru/function.str-word-count.html
I needed a function which would extract the first hundred words out of a given input while retaining all markup such as line breaks, double spaces and the like. Most of the regexp based functions posted above were accurate in that they counted out a hundred words, but recombined the paragraph by imploding an array down to a string. This did away with any such hopes of line breaks, and thus I devised a crude but very accurate function which does all that I ask it to:

function Truncate($input, $numWords) 
{
  if(str_word_count($input,0)>$numWords)
  {
    $WordKey = str_word_count($input,1);
    $PosKey = str_word_count($input,2);
    reset($PosKey);
    foreach($WordKey as $key => &$value)
    {
        $value=key($PosKey);
        next($PosKey);
    }
    return substr($input,0,$WordKey[$numWords]);
  }
  else {return $input;}
}

The idea behind it? Go through the keys of the arrays returned by str_word_count and associate the number of each word with its character position in the phrase. Then use substr to return everything up until the nth character. I have tested this function on rather large entries and it seems to be efficient enough that it does not bog down at all.

Cheers!

Josh
2007-03-02 19:02:19
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Here's a very fast word limiter function that preserves the original whitespace.

<?php

function word_limiter($str$limit 100$end_char '&#8230;') {
   
    if (
trim($str) == '')
        return 
$str;
   
   
preg_match('/\s*(?:\S*\s*){'. (int) $limit .'}/'$str$matches);

    if (
strlen($matches[0]) == strlen($str))
       
$end_char '';

    return 
rtrim($matches[0]) . $end_char;
}

?>

For the thought process behind this function, please read: http://codeigniter.com/forums/viewthread/51788/

Geert De Deckere
2007-05-28 07:52:06
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This is an update to my previously posted word_limiter() function. The regex is even more optimized now. Just replace the preg_match line. Change to:

<?php
preg_match
('/^\s*(?:\S+\s*){1,'. (int) $limit .'}/'$str$matches);
2007-06-13 12:04:03
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
A cute little function for truncating text to a given word limit:
<?php
   
function limit_text($text$limit) {
      if (
strlen($text) > $limit) {
         
$words str_word_count($text2);
         
$pos array_keys($words);
         
$text substr($text0$pos[$limit]) . '...';
      }
      return 
$text;
    }
?>
2007-07-19 16:16:46
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
<?php

/**
 * Returns the number of words in a string.
 * As far as I have tested, it is very accurate.
 * The string can have HTML in it,
 * but you should do something like this first:
 *
 *    $search = array(
 *      '@<script[^>]*?>.*?</script>@si',
 *      '@<style[^>]*?>.*?</style>@siU',
 *      '@<![\s\S]*?--[ \t\n\r]*>@'
 *    );
 *    $html = preg_replace($search, '', $html);
 *
 */

function word_count($html) {

 
# strip all html tags
 
$wc strip_tags($html);

 
# remove 'words' that don't consist of alphanumerical characters or punctuation
 
$pattern "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#";
 
$wc trim(preg_replace($pattern" "$wc));

 
# remove one-letter 'words' that consist only of punctuation
 
$wc trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#"" "$wc));

 
# remove superfluous whitespace
 
$wc preg_replace("/\s\s+/"" "$wc);

 
# split string into an array of words
 
$wc explode(" "$wc);

 
# remove empty elements
 
$wc array_filter($wc);

 
# return the number of words
 
return count($wc);

}

?>
2007-12-08 22:01:08
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
there was a glitch in the code cathy put a post or two ago... should be:

    function limit_text($text, $limit) {
    $text = strip_tags($text);
      $words = str_word_count($text, 2);
      $pos = array_keys($words);
      if (count($words) > $limit) {
          $text = substr($text, 0, $pos[$limit]) . ' ...';
      }
    return $text;
    }

I also added the strip tags in case there is html in there to gum up the works
2007-12-24 15:13:13
http://php5.kiev.ua/manual/ru/function.str-word-count.html
function count_words($texte)
{
$texte=trim($texte);
$motsinutiles = array(' * ', ' - ', ' : ', '\n');
$texte = str_replace($motsinutiles, '', $texte);
$texte = preg_replace("/\s\s+/", " ", $texte);
$decoupeapostrophes = count(explode('\'', $texte)); //On découpe la chaine en apostrophes
   if($decoupeapostrophes==0) $nombreapostrophes = 0;
   if ($decoupeapostrophes%2==0) {$nombreapostrophes = $decoupeapostrophes/2;}
   else  $nombreapostrophes = ($decoupeapostrophes/2)-0.5;
$nombreespace = count(explode(' ', $texte));

return $nombreespace+$nombreapostrophes;   
}
2008-03-30 09:21:31
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
str_word_count: mixed (string string, [int format], [string charlist])

It can help you to solve problem with digest and some locales. Best regards.
2008-06-17 07:21:31
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
Fix Cathy function bug.

Original Cathy function :
[code]
<?php
   
function limit_text($text$limit) {
      if (
strlen($text) > $limit) {
         
$words str_word_count($text2);
         
$pos array_keys($words);
         
$text substr($text0$pos[$limit]) . '...';
      }
      return 
$text;
    }
?>
[/code]

This function return undefined index if $limit < $text.

For fix it :
[code]
<?php
   
function limit_text($text$limitstr$limitwrd) {
      if (
strlen($text) > $limitstr) {
         
$words str_word_count($text2);
          if (
$words $limitwrd) {
             
$pos array_keys($words);
             
$text substr($text0$pos[$limitwrd]) . '...';
          }
      }
      return 
$text;
    }
?>
[/code]
2008-09-06 05:52:19
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Here is a code for a function str_word_count() compatible with UTF-8. I'm sorry that the comments are in French because I am not very good in English: anyway, these comments only try to explain things that are in PCRE or Unicode documentations.

<?php
   
/*
     * Explications du masque pour preg_match_all.
     *
     * La fonction str_word_count standard considère qu'un mot est
     * une séquence de caractères qui contient tous les caractères
     * alphabétiques, et qui peut contenir, mais pas commencer
     * par "'" et "-".
     *
     * Avec Unicode et UTF-8, une lettre peut être un caractères
     * ASCII non accentué tel que "e" ou "E", mais aussi un "é" ou
     * un "É", lequel peut se représenter sous la forme de deux
     * caractères : d'abord le "E" non accentué, puis l'accent tout
     * seul. Une lettre "E" ou "É" fait partie de la classe « L »,
     * un accent de la classe « Mn ».
     *
     * Par ailleurs, "-" n'est plus le seul trait d'union possible.
     * Plutôt que de les lister individuellement, j'ai choisi de
     * tester les caractères de la classe « Pd ». Un inconvénient
     * est que cela inclut aussi le tiret cadratin et d'autres,
     * mais cet inconvénient existait déjà avec str_word_count et
     * le tiret ascii, et en outre il ne concerne pas le français
     * (contrairement à l'anglais, il y a toujours des espaces
     * autour de ces tirets).
     *
     * Enfin, "'" n'est pas non plus la seule apostrophe possible.
     * Mais contrairement aux tirets je teste juste l'apostrophe
     * typographique U+2019 à part au lieu de tester la classe « Pf »
     * car cette dernière contient trop de signes de ponctuation
     * à exclure de la définition d'un mot.
     *
     * Un mot commence donc par une lettre \p{L}, éventuellement
     * accentuée (suivie par un nombre quelconque de \p{Mn}), et
     * ensuite on peut rencontrer un nombre quelconques d'autres
     * lettres (\p{L} et \p{Mn}), de tirets (\p{Pd}) ou d'apostrophes
     * (' et \x{2019}). Tout ceci, bien sûr, dans un masque compatible
     * avec UTF-8 (/u à la fin).
     *
     * Pour les références, voir :
     * http://fr2.php.net/manual/fr/regexp.reference.php #regexp.reference.unicode
     * http://fr2.php.net/manual/fr/reference.pcre.pattern.modifiers.php
     */
   
define("WORD_COUNT_MASK""/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");

    function 
str_word_count_utf8($str)
    {
        return 
preg_match_all(WORD_COUNT_MASK$str$matches);
    }
2008-09-06 17:29:19
http://php5.kiev.ua/manual/ru/function.str-word-count.html
The previous function str_word_count_utf8 implemented only the first parameter, $string. Here is an implementation which also supports the second parameter, $format. The $charlist is not supported, though it could be possible to give the possibility to change the MASK.

<?php
    define
("WORD_COUNT_MASK""/\p{L}[\p{L}\p{Mn}\p{Pd}'\x{2019}]*/u");

    function 
str_word_count_utf8($string$format 0)
    {
        switch (
$format) {
        case 
1:
           
preg_match_all(WORD_COUNT_MASK$string$matches);
            return 
$matches[0];
        case 
2:
           
preg_match_all(WORD_COUNT_MASK$string$matchesPREG_OFFSET_CAPTURE);
           
$result = array();
            foreach (
$matches[0] as $match) {
               
$result[$match[1]] = $match[0];
            }
            return 
$result;
        }
        return 
preg_match_all(WORD_COUNT_MASK$string$matches);
    }
?>

Note that in the case $format=2 the numeric positions are expressed in octets, not in characters.
2008-09-07 16:23:45
http://php5.kiev.ua/manual/ru/function.str-word-count.html
For spanish speakers a valid character map may be:

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

$count str_word_count($text0$characterMap);
?>
2008-12-22 05:06:26
http://php5.kiev.ua/manual/ru/function.str-word-count.html
My quick and rough wordLimiter function.

<?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;
}
?>
2009-01-11 02:37:32
http://php5.kiev.ua/manual/ru/function.str-word-count.html
We can also specify a range of values for charlist.

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

will give the result as 

Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )
2009-02-05 04:32:57
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
Personally, I dont like using this function becuase the characters it omits are sometime nessesery for instance MS Word counts ">" or "<" alone as single word where this function doesnt. I like using this however, it counts EVERYTHING:

<?php
function num_words($string){
   
preg_match_all("/\S+/"$string$matches);
    return 
count($matches[0]);
}
?>
2009-04-13 13:39:05
http://php5.kiev.ua/manual/ru/function.str-word-count.html
I like your function eanimator but it got a little mistake - before the dots it putted another space.
This is a version with "bug" repaired:

<?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]." ";
    }
    if (
$dots) {
       
$string substr($string0strlen($string));
    }

    return 
$string.$dots;
}
?>
2009-07-05 15:08:41
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Hi this is the first time I have posted on the php manual, I hope some of you will like this little function I wrote.

It returns a string with a certain character limit, but still retaining whole words.
It breaks out of the foreach loop once it has found a string short enough to display, and the character list can be edited.

<?php
function word_limiter$text$limit 30$chars '0123456789' ) {
    if( 
strlen$text ) > $limit ) {
       
$words str_word_count$text2$chars );
       
$words array_reverse$wordsTRUE );
        foreach( 
$words as $length => $word ) {
            if( 
$length strlen$word ) >= $limit ) {
               
array_shift$words );
            } else {
                break;
            }
        }
       
$words array_reverse$words );
       
$text implode" "$words ) . '&hellip;';
    }
    return 
$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
2009-07-29 07:56:01
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Words also cannot end in a hyphen unless allowed by the charlist...
2010-02-13 01:33:00
http://php5.kiev.ua/manual/ru/function.str-word-count.html
word limiter:

$str = "my hella long string" ;
$length = 3;
$shortened = 
implode(' ',array_slice(str_word_count($str,1),0,$length));
2010-09-26 23:17:15
http://php5.kiev.ua/manual/ru/function.str-word-count.html
to count words after converting a msword document to plain text with antiword, you can use this function:

<?php
function count_words($text) {
   
$text str_replace(str_split('|'), ''$text); // remove these chars (you can specify more)
   
$text trim(preg_replace('/\s+/'' '$text)); // remove extra spaces
   
$text preg_replace('/-{2,}/'''$text); // remove 2 or more dashes in a row
   
$len strlen($text);
   
    if (
=== $len) {
        return 
0;
    }
   
   
$words 1;
   
    while (
$len--) {
        if (
' ' === $text[$len]) {
            ++
$words;
        }
    }
   
    return 
$words;
}
?>

it strips the pipe "|" chars, which antiword uses to format tables in its plain text output, removes more than one dashes in a row (also used in tables), then counts the words.

counting words using explode() and then count() is not a good idea for huge texts, because it uses much memory to store the text once more as an array. this is why i'm using while() { .. } to walk the string
2010-10-18 07:39:36
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This needs improvement, but works well as is.

<?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);
}
?>

example usage:

<?php
$file 
'http://www.php.net/';
// or use a local file, see file_get_contents() for valid filenames and restrictions.

$index index_page($file);
echo 
'<pre>'.print_r($index,true).'</pre>';
?>
2011-04-05 22:08:15
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This function count words. But this function works with UTF-8 too.

<?php

/**
 * @author Zulfugar Ismayilzadeh
 * @copyright 2011
 */

function count_words($string){
   
   
$string trim(preg_replace("/\s+/"," ",$string));
   
   
$word_array explode(" "$string);
   
   
$num count($word_array);
   
   return 
$num;
   
}

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

echo 
count_words($str);

?>
2011-04-14 07:52:06
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This function count words, is quick and works well with utf-8:

    function count_words($string)
    {
        //$string = htmlspecialchars_decode(strip_tags($string)); // optional
        $t = array(' '=>1, '_'=>1, "\x20", "\xA0", "\x0A", "\x0D", "\x09", "\x0B", '='=>1, '+'=>1, '-'=>1, '*'=>1, '/'=>1, '\\'=>1, ','=>1, '.'=>1, ';'=>1, ':'=>1, '"'=>1, '\''=>1, '['=>1, ']'=>1, '{'=>1, '}'=>1, '('=>1, ')'=>1, '<'=>1, '>'=>1, '&'=>1, '%'=>1, '$'=>1, '@'=>1, '#'=>1, '^'=>1, '!'=>1, '?'=>1); // separators
        $count= isset($t[$string[0]])? 0:1;
        for ($i=1;$i<strlen($string);$i++)
            if (isset($t[$string[$i-1]]) && !isset($t[$string[$i]])) // if new word starts
                $count++;
        return $count;
    }
2011-07-10 08:05:05
http://php5.kiev.ua/manual/ru/function.str-word-count.html
This function count words, is quick and works well with utf-8: (this is corrected version from my previous post)

<?php
function count_words($string)
{
   
$string htmlspecialchars_decode(strip_tags($string));
    if (
strlen($string)==0)
        return 
0;
   
$t = array(' '=>1'_'=>1"\x20"=>1"\xA0"=>1"\x0A"=>1"\x0D"=>1"\x09"=>1"\x0B"=>1"\x2E"=>1"\t"=>1'='=>1'+'=>1'-'=>1'*'=>1'/'=>1'\\'=>1','=>1'.'=>1';'=>1':'=>1'"'=>1'\''=>1'['=>1']'=>1'{'=>1'}'=>1'('=>1')'=>1'<'=>1'>'=>1'&'=>1'%'=>1'$'=>1'@'=>1'#'=>1'^'=>1'!'=>1'?'=>1); // separators
   
$count= isset($t[$string[0]])? 0:1;
    if (
strlen($string)==1)
        return 
$count;
    for (
$i=1;$i<strlen($string);$i++)
        if (isset(
$t[$string[$i-1]]) && !isset($t[$string[$i]])) // if new word starts
           
$count++;
    return 
$count;
}
?>
2011-07-10 09:36:47
http://php5.kiev.ua/manual/ru/function.str-word-count.html
Автор:
This is my own version of to get SEO meta description from wordpress post content. it is also generic usage function to get the first n words from a string.

<?php
function my_meta_description($text,$n=10)
{
$text=strip_tags($text);  // not neccssary for none HTML
// $text=strip_shortcodes($text); // uncomment only inside wordpress system
$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;
?>
2012-01-05 11:21:23
http://php5.kiev.ua/manual/ru/function.str-word-count.html
<?php

/***
 * This simple utf-8 word count function (it only counts) 
 * is a bit faster then the one with preg_match_all
 * about 10x slower then the built-in str_word_count
 * 
 * If you need the hyphen or other code points as word-characters
 * just put them into the [brackets] like [^\p{L}\p{N}\'\-]
 * If the pattern contains utf-8, utf8_encode() the pattern,
 * as it is expected to be valid utf-8 (using the u modifier).
 **/

// Jonny 5's simple word splitter
function str_word_count_utf8($str) {
  return 
count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
?>
2012-02-03 23:29:55
http://php5.kiev.ua/manual/ru/function.str-word-count.html

    Поддержать сайт на родительском проекте КГБ