2009-09-17 61 views
0

我試圖在我的內容中匹配<a>標記,然後替換爲鏈接文本,然後用方括號中的網址替換爲打印版本。如果只有「href」,以下示例工作。如果<a>包含另一個屬性,則它匹配得太多並且不會返回所需的結果。我如何匹配URL和鏈接文本,就是這樣?內容中的純文本的固定標記

這裏是我的代碼:

<?php 
$content = '<a href="http://www.website.com">This is a text link</a>'; 
$result = preg_replace('/<a href="(http:\/\/[A-Za-z0-9\\.:\/]{1,})">([\\s\\S]*?)<\/a>/', 
    '<strong>\\2</strong> [\\1]', $content); 
echo $result; 
?> 

期望的結果:

<strong>This is a text link </strong> [http://www.website.com] 

感謝, 傑森

+0

你能用任何答案解決你的問題嗎? – 2009-10-06 15:23:44

+0

謝謝你回來。是的,我能夠使用「?」對於非常規的比賽來獲得理想的結果。這適用於這種特殊情況。不過,我喜歡你解析DOM的方法。我需要充分理解這一點。 – JasonBartholme 2009-10-06 19:59:40

回答

1

您可以進行比賽ungreedy使用?。 您還應該考慮到href屬性之前可能存在的屬性。

$result = preg_replace('/<a [^>]*?href="(http:\/\/[A-Za-z0-9\\.:\/]+?)">([\\s\\S]*?)<\/a>/', 
    '<strong>\\2</strong> [\\1]', $content); 
8

您應該使用DOM來解析HTML,而不是正則表達式...

編輯:更新的代碼做的href屬性值簡單的regex解析。

編輯#2:使循環迴歸,因此它可以處理多個替換。

$content = ' 
<p><a href="http://www.website.com">This is a text link</a></p> 
<a href="http://sitename.com/#foo">bah</a> 

<a href="#foo">I wont change</a> 

'; 


$dom = new DOMDocument(); 
    $dom->loadHTML($content); 

    $anchors = $dom->getElementsByTagName('a'); 
    $len = $anchors->length; 

    if ($len > 0) { 
     $i = $len-1; 
     while ($i > -1) { 
     $anchor = $anchors->item($i); 

     if ($anchor->hasAttribute('href')) { 
      $href = $anchor->getAttribute('href'); 
      $regex = '/^http/'; 

      if (!preg_match ($regex, $href)) { 
      $i--; 
      continue; 
      } 

      $text = $anchor->nodeValue; 
      $textNode = $dom->createTextNode($text); 

      $strong = $dom->createElement('strong'); 
      $strong->appendChild($textNode); 

      $anchor->parentNode->replaceChild($strong, $anchor); 
     } 
     $i--; 
     } 
    } 

    echo $dom->saveHTML(); 
    ?> 
+0

裸露在我身邊,試圖重新格式化它:p – 2009-09-17 16:39:24

+0

終於 - 我們走了。 – 2009-09-17 16:40:10

+0

謝謝你的努力。我需要更多地深入DOM操作。 – JasonBartholme 2009-09-17 18:44:18