2012-01-23 3 views
0

나는 1000 개가 넘는 큰 단어가 있습니다. 내가 필요한 것은 특정 단어를 찾은 다음 변수를 둘러싼 단어를 감싸는 것입니다. 나는이를 어떻게문자열에서 특정 단어를 찾아서 감싸는 것

$in = 'This is a very long sentence, what I need is to find the word "phone" in this sentence, and after that, to wrap some words around it'; 

: 당신이 볼 수 있듯이 나는 단어 "전화"를 찾을 때

$out = 'find the word "phone" in this sentence'; 

그래서, 나는 그 단어의 왼쪽 & 오른쪽 확장합니다. 실제 예제는 google에서 검색어를 작성하고 제목 결과를 작성하고 웹 페이지에서 일부 콘텐츠를 가져 와서 검색어를 굵게 표시하는 것입니다.

+0

어떻게 일치합니까? 정확한 일치, 형태소 분석 및 그러한 정규화? 검색 쿼리의 위치 데이터가 있습니까? –

+0

* 단어 *가 무엇인지 정의하십시오. – hakre

답변

4

여기에 하는 방법입니다. 나는 이것이 최선의 방법이라고 말하지는 않지만 작동 할 것이다. 아마도 "더 좋거나 더 좋을"수있는 정규식 방법이있을 것입니다.

$in = 'This is a very long sentence, what I need is to find the word phone in this sentence, and after that, to wrap some words around it'; 
$wordToFind = 'phone'; 
$numWordsToWrap = 3; 

$words = preg_split('/\s+/', $in); 
if (($pos = array_search($wordToFind, $words)) !== FALSE) { 
    $start = ($pos - $numWordsToWrap > 0) ? $pos - $numWordsToWrap : 0; 
    $length = (($pos + ($numWordsToWrap + 1) < count($words)) ? $pos + ($numWordsToWrap + 1) : count($words) - 1) - $start; 
    $slice = array_slice($words, $start, $length); 
    $out = implode(' ', $slice); 
    echo $out; 
} else echo 'I didn\'t find it'; 
+0

고마워,이 트릭을했다. –

2

이것은 당신이 성취 수있는 방법의 비교적 간단한 예입니다

<?php 

    $in = "blah blah blah test blah blah blah"; 
    $search = "test"; 
    $replace = "--- test ---"; 

    $out = str_replace($search, $replace, $in); 

?> 
2
$out=preg_match('/\w+\s+\w+\s+\w+\s+\"phone\"\s+\w+\s+\w+\s+\w+/',$in,$m); 
if ($out) $out=$m[0]; 

은 따옴표는 선택 사항이며 특수 문자와 관련된 돔 유연성을 원하는

preg_match('/\w+[^\w]+\w+[^\w]+\w+[^\w]+phone[^\w]+\w+[^\w]+\w+[^\w]+\w+/',$in,$m); 

하고있는 경우를 사용하는 경우 부분 일치 단어를 사용하고 싶음

preg_match('/\w+[^\w]+\w+[^\w]+\w+[^\w]+\w*hon\w*[^\w]+\w+[^\w]+\w+[^\w]+\w+/',$in,$m); 

전화에서 "hon"와 일치합니다.

+0

'\ W == [^ \ w]'- 패턴을 읽기 쉽게 만들 수 있습니다. 또한 ['preg_quote'] (http://php.net/preg_quote)에 대한 메모가 유용 할 수 있습니다. – hakre

+0

@hakre 너무 어리석은 일은 미안하지만, 당신의 의견을 받아 들일 필요가 없습니다 –

+0

'[^ \ w] +'를'\ W +'로 바꿀 수 있습니다. 'preg_quote'는 패턴을 깨뜨리지 않도록 검색어를 삽입하는 데 사용할 수 있습니다. – hakre

0
$in = 'This is a very long sentence, what I need is to find the word phone in this  sentence, and after that, to wrap some words around it'; 

$array = explode(" ", $in); 

$how_much = 3; 

$search_word = "phone"; 

foreach ($array as $index => $word) { 
    if ($word == $search_word) { 
     for ($index1 = 0; $index1 < ($how_much * 2) + 1; $index1++) { 
      $key = $index-$how_much+$index1; 
      echo $array[$key]; 
      echo " "; 
     } 
    } 
} 

이 간단한 솔루션입니다. 공백에 문장을 폭발시킨 다음 단어 + $ how_much 단어를 양방향으로 표시하십시오.

5

당신은 문자열에서 특정 단어 (검색 텍스트)를 강조하려면는 다음을 수행 정규식 방법.

PHP 코드 : 스팬 클래스와 일치하는 텍스트 배치되는 본 실시 예 이후

$in = 'This is a very long sentence, what I need is to find the word phone in this sentence, and after that, to wrap some words around it'; 
$wordToFind = 'phone'; 
$wrap_before = '<span class="highlight_match">'; 
$wrap_after = '</span>'; 

$out = preg_replace("/($wordToFind)/i", "$wrap_before$1$wrap_after", $in); 

// value of $out is now: 
// This is a very long sentence, what I need is to find the word <span class="highlight_match">phone</span> in this sentence, and after that, to wrap some words around it 

CSS 코드

여기 의무적 예 CSS 코드

<style type="text/css"> 
    .highlight_match { 
     background-color: yellow; 
     font-weight: bold; 
    } 
</style> 
4
인 @DaveRandom 덕분에

덕분에 코드를 다시 작성하고 다시 작성

<?php 

$in = 'This is a very long sentence, what I need is to find the word phone in this sentence, and after that, to wrap some words around it'; 
$wordToFind = 'words'; 
$numWordsToWrap = 3; 
echo $in; 
echo "<br />"; 
$words = preg_split('/\s+/', $in); 

$found_words = preg_grep("/^".$wordToFind.".*/", $words); 
$found_pos  = array_keys($found_words); 
if(count($found_pos)) 
{ 
    $pos = $found_pos[0]; 
} 

if (isset($pos)) 
{ 
    $start = ($pos - $numWordsToWrap > 0) ? $pos - $numWordsToWrap : 0; 
    $length = (($pos + ($numWordsToWrap + 1) < count($words)) ? $pos + ($numWordsToWrap + 1) : count($words)) - $start; 
    $slice = array_slice($words, $start, $length); 

    $pre_start = ($start > 0) ? "...":"";  

    $post_end = ($pos + ($numWordsToWrap + 1) < count($words)) ? "...":""; 

    $out = $pre_start.implode(' ', $slice).$post_end; 
    echo $out; 
} 
else 
    echo 'I didn\'t find it'; 
?> 

모두 재사용하고 싶을 것입니다.

다시 감사드립니다. DaveRandom에게 감사드립니다.

관련 문제