2014-09-26 42 views
1

我試圖模仿Twitter的哈希標記系統,用可點擊的鏈接替換所有的哈希標籤。我編寫了一個可以工作的片段,但是我發現如果兩個單詞有類似的開頭,那麼較長的單詞只會被替換(通過可點擊的鏈接)到較短單詞停止的長度。即如果我在#toolbox中有一個句子'#tool',#tool變成一個鏈接,只有#toolbox中的#tool變成鏈接,而不是整個#toolbox。php preg_match_all/preg_replace截斷類似匹配的替換

下面是摘錄:

<?php 


//define text to use in preg_match and preg_replace 
$text = '#tool in a #toolbox'; 

//get all words with hashtags 
preg_match_all("/#\w+/",$text,$words_with_tags); 

    //if there are words with hash tags 
    if(!empty($words_with_tags[0])){ 

     $words = $words_with_tags[0]; 

     //define replacements for each tagged word, 
     // $replacement  is an array of replacements for each word 
     // $words   is an array of words to be replaced 
     for($i = 0; $i < sizeof($words) ; $i++){ 

      $replacements[$i] = '<a href="'.trim($words[$i],'#').'">'.$words[$i].'</a>'; 

      // format word as /word/ to be used in preg_replace 
      $words[$i] = '/'.$words[$i].'/'; 
     } 

     //return tagged text with old words replaced by clickable links 
     $tagged_text = preg_replace($words,$replacements,$text); 

    }else{ 
     //there are no words with tags, assign original text value to $tagged_text 
     $tagged_text = $text; 
    } 


echo $tagged_text; 


?> 

回答

1

什麼capturing,並做一個簡單的preg_replace()

$tagged_text = preg_replace('~#(\w+)~', '<a href="\1">\0</a>', $text); 

Test at eval.in輸出到

<a href="tool">#tool</a> in a <a href="toolbox">#toolbox</a> 

Test at regex101

+0

優秀。神奇。謝謝!然而,我仍然困惑,爲什麼我的長期過程不起作用。我希望有人會指出我在代碼中出錯的地方。從理論上講,我輸入的內容應該可以工作(我相信是這樣),但它根本沒有。 – Dara 2014-09-29 19:36:29

+0

@Dara不客氣:)因爲'$ words [$ i] ='/'。'words [$ i]。'/';''忘記添加[單詞界限](http: //www.regular-expressions.info/wordboundaries.html):''/'。'words [$ i]。'\ b /'' – 2014-09-30 09:24:00

+0

太棒了。上帝保佑! – Dara 2014-09-30 17:47:41

0

您可以使用preg_replace_callback

<?php 

$string = "#tool in a #toolbox"; 

$str = preg_replace_callback(
      '/\#[a-z0-9]+/', 
      function ($matches) { 
       return "<a href=\"". ltrim($matches[0], "#") ."\">". $matches[0] ."</a>"; 
      }, $string); 
    echo $str; 
    //Output: <a href="tool">#tool</a> in a <a href="toolbox">#toolbox</a> 

https://eval.in/198848