2012-04-03 98 views
0

我一直在絞盡腦汁,幾個小時,我需要通過一些HTML到一個函數,並取代鏈接和返回與替換鏈接的HTML。php替換鏈接

<?php 
    final static public function replace_links($campaign_id, $text) { 
     $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; 
     if(preg_match_all("/$regexp/siU", $text, $matches, PREG_SET_ORDER)) { 
      foreach($matches as $match) { 
       if(substr($match[2], 0, 2) !== '##') { // ignore the placeholders 
        if(substr($match[2], 0, 6) !== 'mailto') { // ignore email addresses 
         // $match[2] = link address 
         // $match[3] = link text 
         $url = "http://xxx.com/click?campaign_id=$campaign_id&email=##email_address##&next=" . $match[2]; 
         #$text .= str_replace($match[2], $url, $text); 
         #echo $links . "\n"; 
         preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]); 
        } 
       } 
       return $text; 
      } 
     } 
    } 
?> 

當我回顯鏈接時,會顯示所有匹配的鏈接。問題是,我如何使用下面替換的鏈接示例返回完整的HTML。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
</head> 

<body> 
<a href="mailto:sssss">xxxx</a> 
<a href="http://www.abc.com/">xxxx</a> 
<a href="http://www.google.com/yeah-baby-yeah">xxxx</a> 
</body> 
</html> 

應該改爲:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
</head> 

<body> 
<a href="mailto:sssss">xxxx</a> 
<a href="https://xxx.com/click?next=http://www.abc.com/">xxxx</a> 
<a href="https://xxx.com/click?next=http://www.google.com/yeah-baby-yeah">xxxx</a> 
</body> 
</html> 

希望這是有道理的。

由於提前,

凱爾

+0

使用DOM文檔和XPath搶鏈接,它應該是非常簡單的。 – ajreal 2012-04-03 19:26:04

+0

謝謝阿吉萊爾,我會看看它,我已經看到http://stackoverflow.com/questions/5317503/php-preg-replace-find-links-and-add-a-hash-to-it – 2012-04-03 19:28:11

回答

0

不要重新發明輪子只是用這樣的:

http://code.google.com/p/jquery-linkify/

這真的很容易,我使用它,以及

+0

嗨傑羅姆,這需要在處理電子郵件的同時在服務器端。 – 2012-04-03 19:43:29

+0

ARGH我沒有看到它是PHP對此感到抱歉:/但嘗試找到已經存在於PHP中的東西,然後我確定存在;) – 2012-04-03 19:44:37

+0

只是看看可能是:http://www.liamdelahunty.com /tips/php_convert_url_to_link.php – 2012-04-03 19:46:44

0

我對preg_replace瞭解不多,但我需要與您一樣的功能。 更改行:

preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]); 

此:

str_replace($match[0],$url,$text); 

似乎這樣的伎倆。

我只是需要得到該函數的返回,所以:

//$text = preg_replace($match[2], "<a href='$url'>{$match[3]}</a>", $match[2]); 
$text = str_replace($match[0],$url,$text); 
+0

對不起,我忘了告訴你必須更改var $ url。使它成爲像這樣的完整html: url as show eletrodomestico 2012-08-15 16:05:13

+0

嗨,我修改了什麼可在http://stackoverflow.com/questions/5317503/php-preg-replace-find-links-and-add-a-hash-to-it 。不管怎麼說,多謝拉。 – 2012-08-16 19:58:00