note 109733 added to function.str-word-count
| From: | uri at speedy dot net | Date: | Wed, 15 Aug 2012 07:08:21 +0000 |
| Subject: | note 109733 added to function.str-word-count | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-190080@lists.php.net to get a copy of this message | ||
Here is a count words function which supports UTF-8 and Hebrew. I tried other functions but they
don't work. Notice that in Hebrew, '"' and '\'' can be used in
words, so they are not separators. This function is not perfect, I would prefer a function we are
using in JavaScript which considers all characters except [a-zA-Z×-ת0-9_\'\"] as
separators, but I don't know how to do it in PHP.
I removed some of the separators which don't work well with Hebrew ("\x20",
"\xA0", "\x0A", "\x0D", "\x09", "\x0B",
"\x2E"). I also removed the underline.
This is a fix to my previous post on this page - I found out that my function returned an incorrect
result for an empty string. I corrected it and I'm also attaching another function - my_strlen.
<?php
function count_words($string) {
// Return the number of words in a string.
$string= str_replace("'", "'", $string);
$t= array(' ', "\t", '=', '+', '-',
'*', '/', '\\', ',', '.', ';',
':', '[', ']', '{', '}', '(',
')', '<', '>', '&', '%', '$',
'@', '#', '^', '!', '?', '~'); //
separators
$string= str_replace($t, " ", $string);
$string= trim(preg_replace("/\s+/", " ", $string));
$num= 0;
if (my_strlen($string)>0) {
$word_array= explode(" ", $string);
$num= count($word_array);
}
return $num;
}
function my_strlen($s) {
// Return mb_strlen with encoding UTF-8.
return mb_strlen($s, "UTF-8");
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 82.80.136.226
----
Manual Page -- http://www.php.net/manual/en/function.str-word-count.php
Edit -- https://master.php.net/note/edit/109733
Del: integrated -- https://master.php.net/note/delete/109733/integrated
Del: useless -- https://master.php.net/note/delete/109733/useless
Del: bad code -- https://master.php.net/note/delete/109733/bad+code
Del: spam -- https://master.php.net/note/delete/109733/spam
Del: non-english -- https://master.php.net/note/delete/109733/non-english
Del: in docs -- https://master.php.net/note/delete/109733/in+docs
Del: other reasons-- https://master.php.net/note/delete/109733
Reject -- https://master.php.net/note/reject/109733
Search -- https://master.php.net/manage/user-notes.php