blank to all external links

Possible Duplicate:
Grabbing the href attribute of an A element
Parse All Links That Contain A Specific Word In "href" Tag

I'm using the following function to add _blank to all the links on my website.

function targetBlank($text) {
  $return = str_replace('<a', '<a target="_blank"', $text);
  return $return;
}

I'm looking for a solution to apply this function only on external links (not on my domain) instead of all links.


Here's an attempted solution that relies on $_SERVER['HTTP_HOST'] :

function targetBlank($text) {
  if( strpos( $text, $_SERVER['HTTP_HOST'] ) === false )
      return str_replace('<a', '<a target="_blank"', $text);
  return $text;
}

Untested, but it should work. @meager is also correct in that this will produce malformed anchor tags if that tag already has a target defined, however, since it will only operate on html strings that you pass in, then <abbr> and so on should be safe as long as you only pass strings with anchor tags in them.

链接地址: http://www.djcxy.com/p/76724.html

上一篇: 替换替换锚文本

下一篇: 对所有外部链接空白