Ruby vs PHP : count the number of words in a text
This is the first article of a serie of comparisons between PHP and Ruby.
Count the number of words in a text is much more complex than what you should think first.
Because a space doesn’t mean a new word everytime. There can be interrogation points with spaces before and after for example. And an interrogation point isn’t a word.
Here, we’ll take the following definition for “word” :
Two or more characters with at least one alphabetical character..
In other words : at leat two characters with at least one letter of the alphabet.
Let’s count our words in Ruby :
class String
def nb_words
self.split(/[a-z]+/).size
end
end
To count the number of words, we only have to do :
puts "my string ! Great no ?".nb_words
Which will then give us 4 and not 6. “!” and “?” aren’t words.
Let’s now do the same thing in PHP.
Even though I don’t think it’s a good idea as there’s the function str_word_count.
function nb_words($string) {
return count(preg_split('[a-z]+’, $string));
}
To be used like the following :
echo nb_words('my string ! Great no ?');




