Press "Enter" to skip to content

php高亮一段文本的关键字,不区分大小写,支持汉字,替换字母大小写不改变

Last updated on 2019-05-16

<?php
/**
 * 高亮一段文本的关键字,不区分大小写,支持汉字
 * @param string $subject 要搜索的字符串
 * @param string $keyword 关键词
 * @param string $pre
 * @param string $suf
 * @return string
 */
function str_highlight($subject, $keyword, $pre = '<font color="red">', $suf = '</font>')
{
    if (empty($subject) || empty($keyword)) {
        return $subject;
    }

    $k_len = strlen($keyword);
    if ($k_len > strlen($subject)) {
        return $subject;
    }

    $keyword = strtolower($keyword);
    $offset  = 0;
    $return  = array();
    while (1) {
        $sub = substr($subject, $offset, $k_len);
        if (strlen($sub) < $k_len) {
            if ($sub) {
                $return[] = $sub;
            }
            break;
        }

        if (strtolower($sub) == $keyword) {
            $return[] = $pre;
            $return[] = $sub;
            $return[] = $suf;

            $offset += $k_len;
        } else {
            $return[] = substr($subject, $offset, 1);
            $offset++;
        }
    }//end while

    return join('', $return);
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *