我一直在絞盡腦汁,幾個小時,我需要通過一些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>
希望這是有道理的。
由於提前,
凱爾
使用DOM文檔和XPath搶鏈接,它應該是非常簡單的。 – ajreal 2012-04-03 19:26:04
謝謝阿吉萊爾,我會看看它,我已經看到http://stackoverflow.com/questions/5317503/php-preg-replace-find-links-and-add-a-hash-to-it – 2012-04-03 19:28:11