A
Anonymous
Guest
This is a really trivial matter which I could do in an instant in other languages. How do I count the number of space characters in a string to get the word count?
$subject = trim( "some words");
check_subject($subject);
function check_subject($subject) {
$subject = trim($subject);
if ((substr_count($subject," ")<1) OR (substr_count($subject," ")>6)){
// Less than one word or more than 6
echo "wrong number of words";
exit;
}
<?php
function get_num_words($string) {
$string = trim($string);
$words = explode(' ', $string);
return count($words);
}
echo get_num_words(" Testing Test Hello Goodbye! ");
?>
<?php
function get_num_words($string) {
$string = trim($string);
$string = ereg_replace(" {1,}", " ", $string);
$words = explode(' ', $string);
return count($words);
}
echo get_num_words(" Testing Test Hello Goodbye! ");
?>