Re: counting ocuring words in a string

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux