Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

[PHP] 특정 단어를 기준으로 앞 뒤로 일정 수의 문자열 가져오기

2015-10-26 by 편리

오늘도 역시 제목 짓는 게 가장 어렵다는 것을 느끼면서.. 삽질의 결과물을 올려본다. 구글에서 검색을 해보면 검색 결과에 검색어가 들어간 내용 중 일부를 보여주는 것을 알 수 있다. 그런 것을 구현해 보고 싶었다. 물론 아래 코드는 아주 기본적이고 간단한 코드이다. 좀 더 구현하고 싶은 게 있긴 한데.. 그건 좀 더 생각을 정리해야 할 필요가 있기 때문에 우선 지금까지 해본 것만 기록으로 남긴다.

데모 : http://codepub.net/php/partialString.php

<?php
function partialString($str, $search, $addLength=5, $addString='...')
{
    list($before, $after) = explode($search, $str);

    $before = rtrim($before);
    $after  = ltrim($after);

    $arr_before = array_reverse(explode(' ', $before));
    $arr_after  = explode(' ', $after);

    $count_before = count($arr_before);
    $count_after  = count($arr_after);

    $before_string = '';
    if($count_before < $addLength) {
        $before_string = implode(' ', $arr_before);
    } else {
        for($i=0; $i<$addLength; $i++) {
            $before_string = $arr_before[$i] . ' ' . $before_string;
        }
    }

    $after_string = '';
    if($count_after < $addLength) {
        $after_string = implode(' ', $arr_after);
    } else {
        for($i=0; $i<$addLength; $i++) {
            $after_string = $after_string . $arr_after[$i] . ' ';
        }
    }

    $string = ($before_string ? $addString : '') . $before_string . $search . ' ' . $after_string . ($after_string ? $addString : '');

    return $string;
}

$str = 'PHP is a popular general-purpose scripting language that is especially suited to web development. Fast, flexible and pragmatic, PHP powers everything from your blog to the most popular websites in the world.';
$search = 'Fast';

echo str_replace($search, '<strong>'.$search.'</strong>', partialString($str, $search));
?>

위 코드를 실행하면 데모에서도 확인할 수 있듯이 …especially suited to web development. Fast , flexible and pragmatic, PHP … 라고 출력이 된다. 이 코드를 가지고 좀 더 지지고 볶으면 좀 더 멋진 기능을 할 수 있을 것 같은데.. 오늘은 피곤하니까 이만..!!

Post navigation

Previous Post:

한계는 시도하지 않았기 때문에 만들어진다.

Next Post:

드디어 나에게도 iPhone 6s plus

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • SK 세븐모바일 유심 셀프교체
  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes