Add _blank to all external links [duplicate]

徘徊边缘 提交于 2019-12-02 04:36:49

问题


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:


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.



来源:https://stackoverflow.com/questions/11162016/add-blank-to-all-external-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!