How to count number of words in a string?

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?
 
Yep, tried that but it seems my ISP has replaced 4.3 with an earlier version, dammit. But thanks for taking the trouble to reply (on a Sunday!)

So I'm working on something like this:

Code:
$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;
	}
 
This doesn't cover all instances, but could modify something like this:

Code:
<?php

function get_num_words($string) {

$string = trim($string);
$words = explode(' ', $string);
return count($words);
}

echo get_num_words(" Testing Test Hello Goodbye!   ");
?>

Hope it helps.
 
Yep, thanks. Been trying "explode" but if there's more than one space between words it explodes each space! So the count ends up wrong. Mind you, my first example also does that. No big deal but not perfect.

Martin
 
Aha! Try this:

Code:
<?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!   ");
?>
 
By the way, I see you aren't far away. I'm in Sandbach only 2 miles from M6 jn 17. :)
 
I did read the examples but the PHP version on my server doesn't support str_word_count(). Also I couldn't understand the examples. :(
A bit above my current level. :help:
 
Back
Top