Recommend this page to a friend! |
All requests | > | What is the best PHP count words class? | > | Request new recommendation | > | Featured requests | > | No recommendations |
by Omotayo Odupitan - 7 years ago (2016-10-25)
+2 | I need to count the number of words in a string. |
1. by Oleg Zorin - 7 years ago (2016-10-27) Reply
Good day, Omotayo Odupitan.
<code>
<?php
function wordsCounter($string) {
$string = preg_replace('/[^[:alpha:]]+/', ' ', $string);
return count(explode(' ', $string));
}
2. by Omotayo Odupitan - 7 years ago (2016-10-27) in reply to comment 1 by Oleg Zorin Comment
Thank you Oleg Zorin.
Much appreciated.
3. by Chiranjeevi Kanaka - 7 years ago (2016-11-02) in reply to comment 1 by Oleg Zorin Comment
what if word contains integers or hyphen. Your function would count them as different words. Instead try this.
<code> <?php
function contains_alpha($item) {
preg_match('[a-zA-Z]+', $item, $matches);
return empty($matches) ? False : True;
}
function wordsCounter($str) {
$str = split('\s+', $str);
$str = array_filter($str, 'contains_alpha')
return count($str);
}
4. by Oleg Zorin - 7 years ago (2016-11-02) in reply to comment 3 by Chiranjeevi Kanaka Comment
[a-zA-Z] it works only with latin alfabet. But 'Ёжик' (small hedgehog) is also a word :).
But in general, I like your variant.
5. by Oleg Zorin - 7 years ago (2016-11-02) in reply to comment 4 by Oleg Zorin Comment
Oops, phpclasses uses ISO-8859-1 charset (it doesn'y support cyrillic chars)
0 | by zinsou A.A.E.Mose 5850 - 7 years ago (2017-06-20) Comment This class got a method which allows to get an array of all the words in a string.The words are indexed so if you need to count them the first way is to see the last index and add 1 since PHP array start indexing at 0 or simply use the function count() of PHP on the array. |
+2 | by Manuel Lemos 23975 - 7 years ago (2016-10-31) Comment If you need a package that works well with UTF-8 and does not depend on the PHP extensions avaliable on your system, that package can solve your problem of counting words. |
1. by Omotayo Odupitan - 7 years ago (2016-10-31) Reply
Thanks Manuel.
Recommend package | |
|