Substring of string using whole words and a max number of characters

<?php
/**
 * Take substring from string containing whole words
 * and keep it shorter or equal to a specified length
 * If only one word is longer than the limit it will be truncated
 *
 * @param unknown_type $str
 * @param unknown_type $max
 * @return unknown
 */
function _substring_words_max($str, $max = ADWORDS_DESCRIPTION) {

  if(
mb_strlen($str) > $max) {
   
// the string is over max number of characters
     
$words = explode(" ", $str);
      foreach(
$words as $wordnr => $word) {
         
$result .= $word." ";
          if (isset(
$words[($wordnr+1)]) AND (mb_strlen($result) + mb_strlen($words[($wordnr+1)])) > $max) {
              break;
          }
      }
      if(
mb_strlen($result) > $max) { $result = substr($result, 0, $max); }//even the first word is larger than the limit, truncated
     
     
$result = trim($result);
     
      return
$result;
  }
 
// if we reach this, the string is below limit
 
return $str;
}
?>