PHP eregi and eregi_replace confusion

128 Views Asked by At

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.

1

There are 1 best solutions below

1
On BEST ANSWER

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);