2012-05-16 35 views
0

大家好我有一個問題 我有一個文本的Preg替換文本鏈接與域濾波

$text = " some and text http://www.somelink2.com/html5.jpg and some text http://www.somelink.net/test/testjava/html5.html#fbid=QTb-X6fv5p1 some http://www.somelink4.org test and http://www.somelink3.org/link.html text and some text "; 

我需要改造所有文本鏈接HTTP/S exept域somelink3.org,somelink2.com他們必須純文本

像這樣的事情,但與域過濾器,而不是extention圖片:

function livelinked ($text){ 
     preg_match_all("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)|^(jpg)^#ie", $text, $ccs); 
     foreach ($ccs[3] as $cc) { 
      if (strpos($cc,"jpg")==false && strpos($cc,"gif")==false && strpos($cc,"png")==false) { 
       $old[] = "http://".$cc; 
       $new[] = '<a href="http://'.$cc.'" target="_blank">'.$cc.'</a>'; 
      } 
     } 
     return str_replace($old,$new,$text); 
} 

編輯:幫我:

$text = preg_replace("~((?:http|https|ftp)://(?!site.com|site2.com|site3.com)(?:\S*?\.\S*?))(?=\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)~i",'<a href="$1" target="_blank">$1</a>',$text); 

回答

1

對於這種情況,您可以使用(?!...) negative lookahead assertion。只需在協議佔位符://後立即添加(?!somelink3.org|somelink2.com)即可。

#((http|https|ftp)://(?!domain1|domain2)(\S*?\.\S*?)).... 

而且你不應該結合笨拙str_replace二次步驟中使用preg_match_all。而是利用preg_replace_callback並將所有邏輯放在一個函數中。

+0

非常感謝,iv gor a succes,我有一些問題:爲什麼它不好使用preg match?當我發佈2個鏈接時得到了一個'www.domain.com/test-ajax-upload.html「target =」_ blank「> www.domain.com/test-ajax-upload.html www.domain.com/test- ajax-upload.html「target =」_ blank「> www.domain.com/test-ajax-upload.html' – devcline

+0

(1)因爲它很笨拙。 (2)因爲你也匹配'\ s'空格字符。 – mario

0

你或許可以凝結下來並使用預浸料全部更換

原正則表達式

(?:http|https|ftp):// 
(\S*?\.(?:(?!(?<=\.)(?:jpg|png|gif)|\s).)*?) 
(?= [\s;)\]\[{},"':<] | $ | \.\s) 

原料替代

<a href="http://$1" target="_blank">$1</a> 

修飾符// XSG

編輯: - 所以我沒有抓到你需要fi過濾域。上面的正則表達式可以過濾jpg/png/gif文件,而且它相當複雜。但添加過濾器可能會更好地通過URL解析器或回調中的另一個正則表達式來處理。