Add _blank to all external links [duplicate]

2019-02-26 17:58发布

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.

1条回答
甜甜的少女心
2楼-- · 2019-02-26 18:37

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.

查看更多
登录 后发表回答