function highlight($text, $words = array(), $length = 200) {
    if (!is_array($words)) $words = array($words);
    $searchText = strtolower(removeAccents($text));
    $searchWord = strtolower(removeAccents($words[0]));
    $startPos = 0;
    
    $prefix = '';
    $postfix = '...';

    mb_ereg_search_init($searchText, '\b'.$searchWord.'\b');
    $res = mb_ereg_search_pos();
    $pos = false;
    if (is_array($res)) {
        $posBytes = $res[0];
        $before = substr($text, 0, $posBytes);
        $pos = mb_strlen($before);
    }
    
    if ($pos !== false) {
        $startPos = $pos - 60;
        if ($startPos < 0) $startPos = 0;
        $left = mb_strlen($searchText) - $startPos;
        if ($left < $length) {
            $startPos -= ($length - $left);
            if ($startPos < 0) {
                $startPos = 0;
            }
        }
        if ($startPos > 0) $prefix = '...';
        $text = mb_substr($text, $startPos, $length);
        $text = highlightWords($text, $words);
        return $prefix.$text.$postfix;
    }
    return $prefix.mb_substr($text, $startPos, $length).$postfix;
}

function highlightWords($text, $words, $prefix = '<span class="highlight">', $postfix = '</span>') {
    foreach ($words as $word) {
        // highlight each word
        $pos = mb_stripos_words_accents($text, $word);
        if ($pos !== false) $text = mb_substr($text, 0, $pos).$prefix.mb_substr($text, $pos, mb_strlen($word)).$postfix.mb_substr($text, $pos + mb_strlen($word));
    }
    return $text;
}

function mb_stripos_words_accents($haystack, $needle) {
    $haystack = strtolower(removeAccents($haystack));
    $needle = strtolower(removeAccents($needle));
    mb_ereg_search_init($haystack, '\b'.$needle.'\b');
    $res = mb_ereg_search_pos();
    if (is_array($res)) return $res[0];
    return false;
}

function removeAccents($string) {
    $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
    $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
    return str_replace($search, $replace, $string);
}