Append class="external" to external links
What is the php code to append class="external" to links that ar开发者_运维知识库e posted and are not the domain.
For example my site is www.mysite.com and you post a link to www.mysite.com/news and a link to www.yoursite.com
How do I set it so only non "mysite.com" links have the class specified?
Another approach would be using CSS3 selectors but they are not supported by Internet Explorer 6 (see: http://www.webdevout.net/browser-support-css#css3selectors):
// external link style
a:link[href^="http://"] {
background-color: #990000;
}
// internal link style
a:link, a:link[href^="http://www.mydomain.com"] {
background-color: #009900;
color: #000000;
}
You would not need to change your links programmatically!
<a href="somelink.htm">some link</a>
<a href="http://www.mydomain.com/anotherlink.htm">another link</a>
... would result in a link with internal link style.
<a href="http://www.otherdomain.com">external link</a>
... would result in a link with external link style.
One way is to check the contents of the URL for "http://" (or "https://")
In fact, also check that it does NOT contain your domain name (in case you may have fully-qualified an internal link.)
In PHP, use strpos()
Could also be approached on the client-side using the same general technique. (JQuery is an obvious option since it involves adding a class.)
Don't parse html with regular expressions. Really. RegEx match open tags except XHTML self-contained tags
Use a DOM parser like this one: http://simplehtmldom.sourceforge.net/
$html = $xxxx //load it from your db or wherever it is
$dom = new simple_html_dom();
$dom->load($html);
foreach($dom->find('a') as $a) {
$a->class = 'external';
}
done!
could also use regular expressions to test if your domain name exists in the url, if false then its external. the function for php is preg_match()
精彩评论