Re: counting ocuring words in a string

From: Date: Tue, 17 May 2005 13:55:57 +0000
Subject: Re: counting ocuring words in a string
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-215393@lists.php.net to get a copy of this message
On Tue, 2005-05-17 at 06:00, Merlin wrote: > Hi there, > > I am trying to find a way to count the number of times (if any) words are inside > a string. So I played around with ereg, preg_match_all and so on, but could not > put together a working code. Maybe something like this? <?php $words = array("php", "language"); $str = 'One language which is great is php. PHP works great!'; $str = strtolower($str); echo '<pre>'; foreach($words as $word) { echo 'word = ' .$word; echo ' (' . substr_count($str, $word). ")\n"; } echo '</pre>'; ?> Although you'll run into a problem if your words array contains for example 'air' which will match both 'air' and 'fair', -- s/:-[(/]/:-)/g Brian GnuPG -> KeyID: 0x04A4F0DC | Key Server: pgp.mit.edu ====================================================================== gpg --keyserver pgp.mit.edu --recv-keys 04A4F0DC Key Info: http://gfx-design.com/keys Linux Registered User #339825 at http://counter.li.org

« previous php.general (#215393) next »