2009-01-03 19 views
1

我希望能夠切換這...Can Regex/preg_replace是否可用於將錨標記添加到關鍵字?

My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this keyword here.

要...

My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this [a href="url"]keyword[/a] here.

我不能簡單地取代的 「關鍵詞」 的所有實例,因爲一些被用在現有的錨標籤中或內。

注意:在Linux上使用PHP5 preg_replace。

回答

2

使用正則表達式可能不是解決這個問題的最好辦法,但這裏是一個快速的解決方案:

function link_keywords($str, $keyword, $url) { 
    $keyword = preg_quote($keyword, '/'); 
    $url = htmlspecialchars($url); 

    // Use split the string on all <a> tags, keeping the matched delimiters: 
    $split_str = preg_split('#(<a\s.*?</a>)#i', $str, -1, PREG_SPLIT_DELIM_CAPTURE); 

    // loop through the results and process the sections between <a> tags 
    $result = ''; 
    foreach ($split_str as $sub_str) { 
     if (preg_match('#^<a\s.*?</a>$#i', $sub_str)) { 
      $result .= $sub_str; 
     } else { 
      // split on all remaining tags 
      $split_sub_str = preg_split('/(<.+?>)/', $sub_str, -1, PREG_SPLIT_DELIM_CAPTURE); 
      foreach ($split_sub_str as $sub_sub_str) { 
       if (preg_match('/^<.+>$/', $sub_sub_str)) { 
        $result .= $sub_sub_str; 
       } else { 
        $result .= preg_replace('/'.$keyword.'/', '<a href="'.$url.'">$0</a>', $sub_sub_str); 
       } 
      } 
     } 
    } 
    return $result; 
} 

的總體思路是分裂串入鏈接和一切。然後將鏈接標記之外的所有內容分解爲標記和純文本,並將鏈接插入純文本。這將阻止[p class =「keyword」]擴展爲[p class =「[a href =」url「] keyword [/ a]」]。

再次,我會嘗試找到一個不涉及正則表達式的簡單解決方案。

2

你不能單獨使用正則表達式來做到這一點。正則表達式無上下文 - 它們只是匹配模式,而不考慮周圍環境。要做你想做的事情,你需要將源代碼解析爲抽象表示,然後將其轉換爲目標輸出。

+0

無法使用「前視」和「後視」功能來說明匹配圖案的周圍環境嗎? – Joe 2009-01-04 04:35:26

相關問題