将 _blank 添加到所有外部链接 [英] Add _blank to all external links

查看:53
本文介绍了将 _blank 添加到所有外部链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
获取 A 元素的 href 属性
解析所有链接在href"中包含特定单词标签

我正在使用以下函数将 _blank 添加到我网站上的所有链接.

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.

推荐答案

这是一个依赖于 $_SERVER['HTTP_HOST'] 的尝试解决方案:

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;
}

未经测试,但它应该可以工作.@meager 也是正确的,因为如果该标签已经定义了目标,这将产生格式错误的锚标签,但是,因为它只会对您传入的 html 字符串进行操作,然后 和只要你只传递带有锚标签的字符串,那么就应该是安全的.

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.

这篇关于将 _blank 添加到所有外部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆