我想重写/屏蔽我文章中的所有外部url,并添加nofollow和target="_blank"。这样,到外部站点的原始链接就会被加密/屏蔽/重写。
例如,:
original link: www.google.com
rewrite it to: www.mydomain.com?goto=google.comjoomla有一个插件,可以重写外部链接:重写插件。
但我没有利用joomla。请看上面的插件,它做的正是我想要的。
我想要什么?
$article = "hello this is example article I want to replace all external link http://google.com";
$host = substr($_SERVER['HTTP_HOST'], 0, 4) == 'www.' ? substr($_SERVER['HTTP_HOST'], 0) : $_SERVER['HTTP_HOST'];
if (thisIsNotMyWebsite){
replace external url
}发布于 2013-02-20 05:16:46
您可以使用DOMDocument解析和遍历文档。
function rewriteExternal($html) {
// The url for your redirection script
$prefix = 'http://www.example.com?goto=';
// a regular expression to determine if
// this link is within your site, edit for your
// domain or other needs
$is_internal = '/(?:^\/|^\.\.\/)|example\.com/';
$dom = new DOMDocument();
// Parse the HTML into a DOM
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
if (!preg_match($is_internal, $href)) {
$link->getAttributeNode('href')->value = $prefix . $href;
$link->setAttributeNode(new DOMAttr('rel', 'nofollow'));
$link->setAttributeNode(new DOMAttr('target', '_blank'));
}
}
// returns the updated HTML or false if there was an error
return $dom->saveHTML();
}这种方法比使用基于正则表达式的解决方案要可靠得多,因为它实际上为您解析DOM,而不是依赖通常脆弱的正则表达式。
发布于 2013-02-20 01:53:27
类似于:
<?php
$html ='1224 <a href="http://www.google.com">google</a> 567';
$tracking_string = 'http://example.com/track.php?url=';
$html = preg_replace('#(<a[^>]+href=")(http|https)([^>" ]+)("?[^>]*>)#is','\\1'.$tracking_string.'\\2\\3\\4',$html);
echo $html; 在这里行动:http://codepad.viper-7.com/7BYkoc
--我的最新消息
<?php
$html =' 1224 <a href="http://www.google.com">google</a> 567';
$tracking_string = 'http://example.com/track.php?url=';
$html = preg_replace('#(<a[^>]+)(href=")(http|https)([^>" ]+)("?[^>]*>)#is','\\1 nofollow target="_blank" \\2'.$tracking_string.'\\3\\4\\5',$html);
echo $html;https://stackoverflow.com/questions/14970744
复制相似问题