메뉴 건너뛰기

프로그램언어

?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

장문의 컨텐트나 게시물에서 특정 단어를 검색했을때 검색어를 포함한 내용의 일부분만을 

검색결과의 가운데 부분에 보이고자 할 경우 필요한 PHP함수를 구현해 보았다.

function search_ellipsis($content, $keyword, $front_num) {

    $keyword_index = mb_strpos($content, $keyword);

    $str_num = $front_num * 2;

    $ellipsis = "";

    $start_index = $keyword_index - $front_num;



    if ($start_index < 0) {

        $str_num += $start_index * -1;

        $start_index = 0;

    }



    if (mb_strlen($content) - $start_index > $str_num) $ellipsis = "......";



    return mb_substr($content, $start_index, $str_num).$ellipsis;

}



$content = "가나다라마바사아자차카타파하abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890";

$keyword = "A";

$result = search_ellipsis($content, $keyword, 10);



echo str_replace($keyword, "<b>".$keyword."</b>", $result);

용법: search_ellipsis(내용, 검색어, 보일글자수);


실행결과:

qrstuvwxyzABCDEFGHIJ......


하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved