2012-08-08 111 views
1

我試圖解決Drupal的主題標籤模塊這個錯誤:http://drupal.org/node/1718154PHP正則表達式匹配字符串中的HTML標籤

我有了這個功能,在我的文字的每一個字由前綴匹配「#」,像#tag:

function hashtags_get_tags($text) { 
    $tags_list = array(); 
    $pattern = "/#[0-9A-Za-z_]+/"; 
    preg_match_all($pattern, $text, $tags_list); 
    $result = implode(',', $tags_list[0]); 
    return $result; 
    } 

我需要忽略網頁內部鏈接,如<a href="#reference">link</a>,或者更一般地,通過#前綴的任何字,一個HTML標籤內出現(所以preceeded通過<,然後是>)。

任何想法我怎麼能做到這一點?

+2

強制性警告:嘗試使用正則表達式匹配HTML會遇到麻煩。爲了在有限的HTML文本中匹配少量文本的主題標籤,我猜最壞的情況可能是看起來內容不合理。但是,這很容易導致錯誤,並且在HTML上使用正則表達式時很容易引入安全問題。非常非常小心。 – 2012-08-08 02:43:58

+0

有人總是鏈接到:[用正則表達式解析HTML](http://stackoverflow.com/a/1732454/1421049)。 – 2012-08-08 03:33:15

+0

實際上,我想我可以限制我的要求:大多數情況下,我想忽略「」標籤中的「#標籤」... – gerlos 2012-08-08 03:34:10

回答

1

您可以先剝離標籤,因爲匹配(使用strip_tags函數)?

function hashtags_get_tags($text) { 

    $text = strip_tags($text); 

    $tags_list = array(); 
    $pattern = "/#[0-9A-Za-z_]+/"; 
    preg_match_all($pattern, $text, $tags_list); 
    $result = implode(',', $tags_list[0]); 
    return $result; 
} 

正則表達式將是棘手的,如果你想只匹配是的HTML標籤內的井號標籤。

0

你可以使用preg_replace

function hashtags_get_tags($text) { 
$tags_list = array(); 
$pattern = "/#[0-9A-Za-z_]+/"; 
$text=preg_replace("/<[^>]*>/","",$text); 
preg_match_all($pattern, $text, $tags_list); 
$result = implode(',', $tags_list[0]); 
return $result; 
} 
0

我做了使用PHP DOM這個函數拋出了前手的標籤。

它返回href中所有有#的鏈接。

如果你想它,只除去內部哈希標籤,更換這行:

if(strpos($link->getAttribute('href'), '#') === false) { 

與此:

if(strpos($link->getAttribute('href'), '#') !== 0) { 

這是函數:

function no_hashtags($text) { 
    $doc = new DOMDocument(); 
    $doc->loadHTML($text); 
    $links = $doc->getElementsByTagName('a'); 
    $nohashes = array(); 
    foreach($links as $link) { 
     if(strpos($link->getAttribute('href'), '#') === false) { 
      $temp = new DOMDocument(); 
      $elem = $temp->importNode($link->cloneNode(true), true); 
      $temp->appendChild($elem); 
      $nohashes[] = $temp->saveHTML(); 
     } 
    } 
    // return $nohashes; 
    return implode('', $nohashes); 
    // return implode(',', $nohashes); 
}