2012-03-21 99 views
1

我有一個有趣的問題,我使用PHP的str_ireplace()突出顯示關鍵字數組中的文本。使用str_ireplace()突出顯示文本

比方說,這是我的關鍵字或短語的數組,我想從一個樣本文字突出:

$keywords = array('eggs', 'green eggs'); 

這是我的示例文本:

$text = 'Green eggs and ham.'; 

這是怎麼了突出顯示文本:

$counter = 0; 
foreach ($keywords as $keyword) { 
    $text = str_ireplace($keyword, '<span class="highlight_'.($counter%5).'">'.$keyword.'</span>', $text); 
    $counter++; 
} 

的問題,這是green eggs永遠得不到上午ATCH因爲eggs已經取代了文字:

Green <span class="highlight_0">eggs</span> and ham. 

也可能有情況下,有部分重疊,例如:

$keywords = array('green eggs', 'eggs and'); 

什麼是一個聰明的方式來解決這類問題的?

+0

一定要注意'綠色雞蛋'否則你有'綠色綠色的蛋' – 2012-03-21 18:35:37

回答

1

顛倒順序:

$keywords = array('green eggs', 'eggs'); 

最簡單的方法是先做最長串並移動到較短的後。只要確保你沒有在同一個字符串上重複(如果重要的話)。

+0

謝謝animuson!我想到了,但如果我們有「綠色雞蛋」和「雞蛋和」呢?我也想照顧存在部分重疊的情況。 – 2012-03-21 18:37:51

1

也許這不是最漂亮的解決方案,但你可以跟蹤在您的關鍵字出現的位置,然後找出它們重疊和調整要包含span標籤

$keywords = array('eggs', 'n eggs a', 'eggs and','green eg'); 
$text = 'Green eggs and ham.'; 
$counter = 0; 
$idx_array = array(); 
$idx_array_last = array(); 
foreach ($keywords as $keyword) { 
    $idx_array_first[$counter] = stripos($text, $keyword); 
    $idx_array_last[$counter] = $idx_array_first[$counter] + strlen($keyword); 
    $counter++; 
} 
//combine the overlapping indices 
for ($i=0; $i<$counter; $i++) { 
    for ($j=$counter-1; $j>=$i+1; $j--) { 
     if (($idx_array_first[$i] <= $idx_array_first[$j] && $idx_array_first[$j] <= $idx_array_last[$i]) 
       || ($idx_array_last[$i] >= $idx_array_last[$j] && $idx_array_first[$i] <= $idx_array_last[$j]) 
       || ($idx_array_first[$j] <= $idx_array_first[$i] && $idx_array_last[$i] <= $idx_array_last[$j])) { 
      $idx_array_first[$i] = min($idx_array_first[$i],$idx_array_first[$j]); 
      $idx_array_last[$i] = max($idx_array_last[$i],$idx_array_last[$j]); 
      $counter--; 
      unset($idx_array_first[$j],$idx_array_last[$j]); 
     } 
    } 
} 
array_multisort($idx_array_first,$idx_array_last); //sort so that span tags are inserted at last indices first 

for ($i=$counter-1; $i>=0; $i--) { 
    //add span tags at locations of indices 
    $textnew = substr($text,0,$idx_array_first[$i]).'<span class="highlight_'.$i.'">'; 
    $textnew .=substr($text,$idx_array_first[$i],$idx_array_first[$i]+$idx_array_last[$i]); 
    $textnew .='</span>'.substr($text,$idx_array_last[$i]); 
    $text = $textnew; 
} 

輸出是

<span class="highlight_0">Green eggs and</span> ham. 
+0

感謝ioums,但我實際上需要保留重疊的每個部分,因爲它必須在文本中進行特殊標記。 – 2012-03-21 20:03:05