[SOLVED] Counting words in a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Archy
Forum Contributor
Posts: 129
Joined: Fri Jun 18, 2004 2:25 pm
Location: USA

[SOLVED] Counting words in a string

Post 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
Last edited by Archy on Tue Feb 01, 2005 12:43 pm, edited 1 time in total.
hunterhp
Forum Commoner
Posts: 46
Joined: Sat Jan 22, 2005 5:20 pm
Contact:

Post by hunterhp »

preg_match_all should do the trick I think.
Archy
Forum Contributor
Posts: 129
Joined: Fri Jun 18, 2004 2:25 pm
Location: USA

Post 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.
Post Reply