Page 1 of 1

[SOLVED] Counting words in a string

Posted: Tue Feb 01, 2005 12:29 pm
by Archy
I have had a look on Google, and on the PHP.net site but couldnt find what I was looking for.

I need a script that counts how many of a certain words there are in a variable. For instance:

How many times the is said in this phrase: " I went to the seaside, and the sea was out. ". So that would return 2.

Anybody have any ideas?
Thanks

Posted: Tue Feb 01, 2005 12:31 pm
by hunterhp
preg_match_all should do the trick I think.

Posted: Tue Feb 01, 2005 12:35 pm
by Archy
If you just want to find out how many times a string contains another simple string, don't use preg_match_all like I did before I fould the substr_count function.

Use
<?php
$nrMatches = substr_count ('foobarbar', 'bar');
?>
instead. Hope this helps some other people like me who like to think too complicated :-)
I dont how I missed that the first time :s
Thanks.