PHP Limit words breaks div in string

I use the following php function to limit word length:

function limit_words($phrase, $max_words) {
   $phrase_array = explode(' ',$phrase);

   if(count($phrase_array) > $max_words && $max_words > 0)
      $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';

   return $phrase;
}

No say I have a string that contains a div or span class e.g.

$string = 'I went to the shop to buy a <span class="highlight">lollipop</span>';

echo limit_words($string,10);

results in:

I went to the shop to buy a <span class="highlight">lollipop

and it’s missing the last div closer </span>

This some times results in messing up my content futher down, is there away to ensure it doesnt cut of the closer tag before it limits the string?

Many thanks