장문의 컨텐트나 게시물에서 특정 단어를 검색했을때 검색어를 포함한 내용의 일부분만을
검색결과의 가운데 부분에 보이고자 할 경우 필요한 PHP함수를 구현해 보았다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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......