note 100468 added to function.str-word-count
| From: | (base64) | Date: | Mon, 18 Oct 2010 11:39:36 +0000 |
| Subject: | note 100468 added to function.str-word-count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-173239@lists.php.net to get a copy of this message | ||
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 (0 === $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
----
Server IP: 217.75.128.29
Probable Submitter: 212.233.135.74
----
Manual Page -- http://www.php.net/manual/en/function.str-word-count.php
Edit -- https://master.php.net/note/edit/100468
Del: integrated -- https://master.php.net/note/delete/100468/integrated
Del: useless -- https://master.php.net/note/delete/100468/useless
Del: bad code -- https://master.php.net/note/delete/100468/bad+code
Del: spam -- https://master.php.net/note/delete/100468/spam
Del: non-english -- https://master.php.net/note/delete/100468/non-english
Del: in docs -- https://master.php.net/note/delete/100468/in+docs
Del: other reasons-- https://master.php.net/note/delete/100468
Reject -- https://master.php.net/note/reject/100468
Search -- https://master.php.net/manage/user-notes.php