728x90

PHP 검색어를 입력하면 색상이 다르게 표시해주는 함수다.

아래 간단한 함수 highlight 와 highlightkeyword 차이를 비교해보면 영문 검색시 차이가 난다. 한글 검색은 highlight 함수로도 충분하다.

네이버스마트 에디터로 작성한 view.php 에서 검색을 해보니 highlight 가 정상적으로 잘 보인다.


<?php
function highlight($text='', $keyword=''){
  if(strlen($text) > 0 && strlen($keyword) > 0) {
    return (str_replace($keyword, "<span style=\"color:red;\">$keyword</span>", $text));
  }
   return ($text);
}

function highlightkeyword($str, $search) {
    // 영어 대문자, 소문자 구분없이 검색
    $highlightcolor = "#FE2E2E";
    $occurrences = substr_count(strtolower($str), strtolower($search));
    $newstring = $str;
    $match = array();
 
    for ($i=0;$i<$occurrences;$i++) {
        $match[$i] = stripos($str, $search, $i);
        $match[$i] = substr($str, $match[$i], strlen($search));
        $newstring = str_replace($match[$i], '[#]'.$match[$i].'[@]', strip_tags($newstring));
    }
 
    $newstring = str_replace('[#]', '<span style="color: '.$highlightcolor.';">', $newstring);
    $newstring = str_replace('[@]', '</span>', $newstring);
    return $newstring;
 
}

$str="진실을 깨닫도록 시도해 보세요... 생명이 느껴지시나요? 생명의 빛을 느껴보세요.";
$str="The을 깨닫도록 시도해 보세요... the 느껴지시나요? the의 빛을 느껴보세요.";
$keyword ='the';
echo highlight($str, $keyword);

echo '<br />';
echo highlightkeyword($str, $keyword);
?>


출처 : https://tomelliott.com/php/highlight-search-keyword-string-function

블로그 이미지

Link2Me

,