0

I'm attempting to count the words in a textarea field. Below is a simple function, that uses the deprecated eregi and eregi_replace.

I know I can swap those two functions with preg_match, and preg_replace, but I'm missing what's after that. I'm sure it's how the parameters are configured.

function count_words($str){
//http://www.reconn.us/count_words.html
$words = 0;
$str = eregi_replace(" +", " ", $str);
$array = explode(" ", $str);
for($i=0;$i < count($array);$i++)
{
if (eregi("[0-9A-Za-zÀ-ÖØ-öø-ÿ]", $array[$i])) 
$words++;
}
return $words;
}

If I understand correctly, for preg_match, I should add "i":

if (preg_match("[0-9A-Za-zÀ-ÖØ-öø-ÿ]/i", $array[$i])) 

But I'm not sure about preg_replace.

coffeemonitor
  • 12,780
  • 34
  • 99
  • 149
  • 4
    `ergi*` functions are deprecated. You switch to `preg*` functions to ensure your software works in the future. – hakre May 28 '12 at 19:55

1 Answers1

1

Counting words can be done way more easily:

$words = mb_split(' +', $text);
$wordCount = count($words);

However, the preg_replace line should be this:

preg_replace('/( +)', ' ', $str);
Jeroen
  • 13,056
  • 4
  • 42
  • 63
  • True, I should have mentioned I also need to know the right way to convert those 2 deprecated functions. There are other places in older code I need to update, appropriately. – coffeemonitor May 28 '12 at 19:49