2011-02-13 2 views
0

일부 기본 html로 300-400 단어의 텍스트가 있다고 가정 해보십시오. 예 :일반 텍스트에 html 링크 추가

<p>text text word1 text text text filament text text text text text text text text</p> 
<p>text text text text text text text text text text text text text text text</p> 

내가 관련된 자신의 URL을 keyphrase를의 목록을 가지고 (약 1000 개의 레코드) 내가 텍스트에서 발견 된 corrispondent 단어의 URL을 배치해야

word1 word2 => 'url' 
house home => 'url1' 
flower filament => 'url2' 

. 예 :

<p>text text <a href="url">word1</a> text [etc..] 

은 내가 간단한 않는 str_replace 또는 preg_replace이다 사용할 수 있습니다 알 수 있습니다. 하지만 나는 많은 링크를 추가하고 싶지 않다. 300-400 단어 중 나는 5-6 개 이상의 링크를 넣고 싶지 않습니다.

어떻게해야합니까?

+0

어떤 기준으로 5-6 링크로 제한 하시겠습니까? –

+0

@pekka 당신은이 질문들로 나를 스토킹하고 있습니다 : D –

+0

정확히 어떻게 의미합니까? 컨텍스트 및 세부 정보를 추가하십시오. :피 –

답변

2

제한 매개 변수를 사용 preg_replace()는 물론 수도 있고 당신이 justs

1

작은 예를 원하는하지 않을 수 있습니다 원하는 각 단어의 첫 번째 인스턴스가 대담하게 첫번째 X 대체 될 것입니다 . 뿐만 아니라 다른 물건을 쉽게 할 수 있어야합니다. :)

<? 
    // Your text 
    $s = <<<YourText 
<p>text text word1 text text text filament text text text text text text text text</p> 
<p>text text text text text text text text text text text text text text text</p> 
YourText; 

    // The words you want to highlight 
    $linkwords = array('text', 'word1', 'filament'); 

    // Split the string by using spaces 
    $words = explode(' ', $s); 
    print_r($words); 

    // Words you have highlighted already. 
    $done = array(); 

    // Loop through all words by reference 
    foreach ($words as &$word) 
    { 
     // Highlight this word? 
     if (array_search($word, $linkwords) !== false) 
     { 
      // Highlighted before? 
      if (array_search($word, $done) === false) 
      { 
       // Remember it.. 
       $done[] = substr($word,0); 
       // And highlight it. 
       $word = '<b>'.$word.'</b>'; 
      } 
     } 
    } 

    echo implode(' ', $words); 
0

첫째, 귀하의 질문에서 나는 단어/주위 60 비율을 연결한다는 생각. 따라서 예를 들어 다음을 수행하십시오.

define('WLRATIO', 60); 

$mytext = "text text ..... "; 
// Rough estimation of word count 
$links = count(explode(' ', $mytext))/WLRATIO; 

$keywords = array(
    'foo' => 'url1', 
    'bar' => 'url2' 
    ... 
); 

$keys = array_keys($keys); 

while ($links--) { 
    $n = rand(0, count($keys)-1); 
    $mytext = preg_replace('/'+$keys[$n]+'/', '<a href="'+$keywords[$keys[$n]]+'">'+$keys[$n]+'</a>', $mytext, 1); 
} 

echo $mytext; 
관련 문제