如何在 ColdFusion 中使用正则表达式用不同的锚点替换所有锚点标签

How to replace all anchor tags with a different anchor using regex in ColdFusion

我在这里发现了一个类似的问题:Wrap URL within a string with a href tags using Coldfusion

但我想做的是在用户将标签提交到服务器后,用稍作修改的版本替换标签。所以这是用户将提交给服务器的一些典型 HTML 文本:

<p>Terminator Genisys is an upcoming 2015 American science fiction action film directed by Alan Taylor. You can find out more by <a href="http://www.imdb.com">clicking here</a></p>

我想做的是用新版本替换 <a href=""> 部分,如下所示:

...
<a href="http://www.imdb.com" rel="nofollow noreferrer">clicking here</a>

所以我只是将文本 rel="nofollow noreferrer" 添加到标签中。

我必须将包含 href 属性的锚标记与 URL 匹配,而不仅仅是 URL 字符串本身,因为有时用户可以这样做:

<p>Terminator Genisys is an upcoming 2015 American science fiction action film directed by Alan Taylor. You can find out more by <a href=""http://www.imdb.com">http://www.imdb.com</a></p>

这样的话我还是只想更换标签。我不想触及实际使用的锚文本,即使它是 URL.

那么我该如何重写这个 Regex

#REReplaceNoCase(myStr, "(\bhttp://[a-z0-9\.\-_:~@##%&/?+=]+)", "<a href=""""></a>", "all")#

反过来,它在哪里选择标签并用我修改过的文本替换它们?

如果您愿意,这对 jQuery(客户端)

来说真的很简单

JSFiddle:http://jsfiddle.net/mz1rwo0u/

$(document).ready(function () {
$("a").each(function(e) {
  if ($(this).attr('href').match(/^https?:\/\/(www\.)?imdb\.com/i)) {
    $(this).attr('rel','nofollow noreferrer');
  }});
});

(如果您右键单击任何 imdb links 和 Inspect Element,您将看到 rel 属性已添加到 imdb links。请注意 View Source 不会反映更改,但 Inspect Element 是重要部分。)

如果你想影响每个 link,你可以这样做。

$(document).ready(function () {
$("a").each(function(e) {
    $(this).attr('rel','nofollow noreferrer');
});
});

最后,您还可以使用选择器缩小范围,您可以将内容加载到 ID 为 contentSection 的 dom 元素中。你可以做...

$(document).ready(function () {
$("#contentSection a").each(function(e) {
  if ($(this).attr('href').match(/^https?:\/\/(www\.)?imdb\.com/i)) {
    $(this).attr('rel','nofollow noreferrer');
  }});
});

在冷聚变中可靠地解析它而不可能意外添加它两次(不调用像 jSoup 这样的工具)有点困难,但是 jQuery 版本是客户端并且通过从中获取数据来工作DOM 而不是试图通过热线连接到它(jSoup 实现的工作方式类似,创建一个可以使用的类似于 DOM 的结构)。

在谈论客户端与服务器端时,您必须考虑未启用 javascript 的虚构用户(或恶意关闭它的用户)。如果此功能不是关键任务。我会使用 JQuery 来做到这一点。当用户在我的网站之一上单击外部 link 时,我使用了类似的功能来弹出警告框。

这是一个 jSoup 实现,快速而粗略。 jSoup 非常适合与 jQuery.

类似的选择方式
<cfscript>
jsoup = CreateObject("java", "org.jsoup.Jsoup");
HTMLDocument = jsoup.parse("<A href='http://imdb.com'>test</a> - <A href='http://google.com'>google</a>");

As = htmldocument.select("a");
for (link in As) {
  if (reFindnoCase("^https?:\/\/(www\.)?imdb\.com",link.attr("href"))) {
    link.attr("rel","nofollow noreferrer");
  }
}
writeOutput(htmldocument);
</cfscript>