2012-04-03 84 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