2010-11-13 92 views
0

我有一個這樣的數組:preg_replace函數和陣列爲多個域

$array = array('domain1.com','domain2.net','domain3.org'); 

任何方式僅更換這些域與preg_replace函數鏈接?

目前這個小功能,但分析所有的域:

   function insert_referer($text){ 
        $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\\1:", $text); 
        $ret = ' ' . $text; 
        $ret = preg_replace("#(^|[\n ])([\w]+?://[\w\#$%&~/.\-;:=,[email protected]\[\]+]*)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $ret); 
        $ret = preg_replace("#(^|[\n ])((www|ftp)\.[\w\#$%&~/.\-;:=,[email protected]\[\]+]*)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $ret); 
        $ret = substr($ret, 1); 
        return $ret; 
       }   

回答

0

此代碼你想要的東西:

 
$array = array('domain1.com','domain2.net','domain3.org'); 
$text = 'Some text including domain1.com/something and http://domain3.org'; 
echo preg_replace('/((?:https?:\/\/)?(?:' . implode('|', $array) . ')[-a-zA-Z0-9\._~:\/?#\[\]@\!\$&\'\(\)\*\+,;=]*)/', '\1', $text); 
// Outputs: 
// "Some text including <a href="domain1.com/something">domain1.com/something</a> and <a href="http://domain3.org">http://domain3.org</a>" 

我沒有測試代碼本身,因此它可能(我不要認爲它可能,但它可能)包含錯別字,但我測試了正則表達式本身,它完美的工作。