note 109722 modified in function.str-word-count by aharvey
| From: | aharvey@php.net | Date: | Wed, 15 Aug 2012 01:51:17 +0000 |
| Subject: | note 109722 modified in function.str-word-count by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190073@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. <?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)); 	$word_array= explode(" ",
$string); 	$num= count($word_array); 	return
$num; } ?>
--was--
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.
<?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));
$word_array= explode(" ", $string);
$num= count($word_array);
return $num;
}
?>
http://php.net/manual/en/function.str-word-count.php