Skip to main content
Participant
February 25, 2011
Answered

REReplaceNoCase Find and append HREF Strings

  • February 25, 2011
  • 1 reply
  • 651 views

I have an index.html file which I am reading via cffile.

I want to search all of the href string and append with a custom string. For example, the file will read a bunch and a href links ( <a href="http://www.google.com">Google</a>,<a href="http://www.yahoo.com">Yahoo</a> etc). I want to be able to append all of the href with something like this (<a href="http://www.mysite.com?redirect=http://www.google.com">Google</a>. I would really appreciate your help in advanced. Thank you.

    This topic has been closed for replies.
    Correct answer pete_freitag

    Something like this should work at a basic level, assuming the HTML is valid:

    <cfset newHTML = ReReplaceNoCase(html, "(href=[""'])([^""']+)([""'])", "\1http://mysite.com/?redir=\2\3", "ALL")>

    It's using backreferences in the regex the parenthesis to group the parts of the match, which are then referred to as \1 \2 and \3 in the replacement string.

    1 reply

    pete_freitag
    pete_freitagCorrect answer
    Participating Frequently
    February 25, 2011

    Something like this should work at a basic level, assuming the HTML is valid:

    <cfset newHTML = ReReplaceNoCase(html, "(href=[""'])([^""']+)([""'])", "\1http://mysite.com/?redir=\2\3", "ALL")>

    It's using backreferences in the regex the parenthesis to group the parts of the match, which are then referred to as \1 \2 and \3 in the replacement string.