Forum Moderators: coopster

Message Too Old, No Replies

Counting Words

         

Gian04

11:43 am on Oct 7, 2007 (gmt 0)

10+ Year Member



Is there a PHP function to count the number of words?

Habtom

11:48 am on Oct 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You can explode the words with space while using the count function to count the number of words exploded.

Gian04

12:01 pm on Oct 7, 2007 (gmt 0)

10+ Year Member



What if the user enter multiple spaces between words, Would it not cause any problem with explode?

PHP_Chimp

1:20 pm on Oct 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



<?php
$str = 'this is a set of words';
$p = '%\s+%';
$t = preg_split($p, $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
echo '<pre>';
print_r($t);
echo '</pre>';

$num_words = count($t);
echo $num_words;
?>

Output -


Array
(
[0] => Array
(
[0] => this
[1] => 0
)
[1] => Array
(
[0] => is
[1] => 5
)
[2] => Array
(
[0] => a
[1] => 8
)
[3] => Array
(
[0] => set
[1] => 10
)
[4] => Array
(
[0] => of
[1] => 14
)
[5] => Array
(
[0] => words
[1] => 17
)
)
6

So this way you can have as many spaces, line breaks or tabs between words.

Habtom

1:55 pm on Oct 7, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What if the user enter multiple spaces between words

You have to make a few cleanups. Spaces, and other symbols which are not likely to be counted as words can be removed while counting.

ayushchd

11:16 am on Oct 8, 2007 (gmt 0)

10+ Year Member



I am not too sure, but would the str_word_count function help you as it returns the number of words in a string..

[php.net...]

mvhemanth

12:42 pm on Oct 8, 2007 (gmt 0)

10+ Year Member



why dont you download a copy of the PHP manual