Re: [PHP] counting ocuring words in a string
On Tuesday 17 May 2005 13: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. Can anybody help me on that? This is the current code: function count_words($str, $words) { if(is_array($words)) { foreach($words as $k = $word) { $pattern[$k] = /\b($word)\b/is; } } else { $pattern = /\b($words)\b/is; } return ereg( $pattern, $str); } $words = 'php language'; $str = 'One language which is great is php. PHP works great!'; $num_hits = count_words($str, $word); echo $num_hits; I would like to get an case insensitive result. In this example: 3 http://www.php.net/manual/en/function.substr-count.php Try this. I am a bit lost on this one. Thank you for any help. Merlin -- Cyberly yours, Petar Nedyalkov Devoted Orbitel Fan :-) PGP ID: 7AE45436 PGP Public Key: http://bu.orbitel.bg/pgp/bu.asc PGP Fingerprint: 7923 8D52 B145 02E8 6F63 8BDA 2D3F 7C0B 7AE4 5436 pgpvE9fqC9aji.pgp Description: PGP signature
Re: [PHP] counting ocuring words in a string
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 BrianGnuPG - 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
Re: [PHP] counting ocuring words in a string
On Tuesday 17 May 2005 18:00, Merlin wrote: I am trying to find a way to count the number of times (if any) words are inside a string. explode() array_count_values() -- Jason Wong - Gremlins Associates - www.gremlins.biz Open Source Software Systems Integrators * Web Design Hosting * Internet Intranet Applications Development * -- Search the list archives before you post http://marc.theaimsgroup.com/?l=php-general -- New Year Resolution: Ignore top posted posts -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php