RE: [PHP] counting matches with eregi() From: Robert V. Zwink (rzwink <email protected>)
Date: 11/15/00

I was going to point you to a function for php4
http://www.php.net/manual/function.substr-count.php

it is used like this

print substr_count("This is a test", "is"); // prints out 2

but the problem is that if you wanted to only match whole words and did
something like

print substr_count("This is a test", " is "); // prints out 1

But if you have a string like this it would break it I think.

print substr_count("is a test", " is "); // would fail

because it wouldn't be a match. Because the string begins with what you are
looking for without the space.

So then I thought that you might be able to do something like this instead

<?php
$string = "my house is a new house but not a big house in my household";

function count_whole_words($haystack, $needle){
        $haystack = explode(" ", $haystack);
        $total = count($haystack);

        for($i=0;$i<$total;$i++){
                if($haystack[$i]==$needle){
                        $j++;
                }
        }
        return $j;
}

echo "Total Found ".count_whole_words($string, "house");

?>

But then I found an even cooler soluction

I hope this helps. Check out the comments at the link above, there are a
couple of interesting solutions in php3 if you need them.

Robert Zwink
<A HREF="zwink.levitate.org"> http://zwink.levitate.org </A>

-----Original Message-----
From: Paul Tuohy [mailto:pablo_100 <email protected>]
Sent: Wednesday, November 15, 2000 10:09 PM
To: php-general <email protected>
Subject: [PHP] counting matches with eregi()

I want to count the number of times a word appears in a string. I am using
php3/linux

Say I have a string:

$string = "my house is a new house but not a big house in my household"

I want to count how many times the word 'house' appears. If I use
parentheses and include a $matches array in an eregi function, it stores
partial matches, not a count of full matches in the entire string.

Also the manual says that word boundary \b should work with php3, but the
series of statments:

$pattern = "\bhouse\b"
$test = eregi($pattern, $string, $matches);

return with no matches. I need to make sure that 'household' is not included
in the count of whole words. what am i doing wrong?

____________________________________________________________________________
_________
Get more from the Web. FREE MSN Explorer download : http://explorer.msn.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: php-general-unsubscribe <email protected>
For additional commands, e-mail: php-general-help <email protected>
To contact the list administrators, e-mail: php-list-admin <email protected>

-- PHP General Mailing List (http://www.php.net/) To unsubscribe, e-mail: php-general-unsubscribe <email protected> For additional commands, e-mail: php-general-help <email protected> To contact the list administrators, e-mail: php-list-admin <email protected>