Re: Counting Words In a String

From: Date: Mon, 23 Apr 2001 08:25:12 +0000
Subject: Re: Counting Words In a String
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-49820@lists.php.net to get a copy of this message
Greg Donald wrote: > > > I want to check a string and return the amount of words present > > in it. These > > strings could be quite large, some higher than 100,000 > > characters. I realize > > I could explode the string on the whitespace and count the number > > of values. > > However, I'm not sure this would be the most optimized way to do this, > > especially considering there will be some quite large strings passed. Any > > ideas on the most efficient to count the number of words in a > > large string? > > $string = "Here is a very long string"; > $array = explode(" ", $string); > $count = sizeof($array); > echo $count; Hello, Greg, Jason asked for an _optimized_ solution. Solution: 1. If you're using PHP>=4.02 just take the substr_count() function (see manual). 2. Otherwise you can take this code: $count=0; for($x=0;$x<strlen($string);$x++) if(substr($string,$x,1)==" ") $count++; if($count>0) $count++; Robert

« previous php.general (#49820) next »