0

I have been trying and searching for answers, but I can't figured it out. I'm trying to replace a link in a (a href="link") with a redirect link (a href="otherlink.com/redirect.cfm?link=link). The link can be http or https. What I have so far is:

 <cfsavecontent variable="s"> 
 This is some text. It is true that <a href="https://www.cnn.com">Harry Potter</a> is a good This is some text. It is true that <a href="http://www.test1.com">Harry Potter</a> is a good This is some text. It is true that <a href="http://www.test2.com">Harry Potter</a> is a good.
 <img src="https://test2.com/assets/img/logos/logo.png"> 
 </cfsavecontent> 

Then I try to find a link and replace it

<cfset replacedText = s.ReplaceAll(
"(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)",
"redirect.cfm?link=URLEncodedFormat($1)"
 ) />

There are a least two things not working: 1. Images (img src) are also included, and I don't want that. 2. I want the original link encoded with URLEncodedFormat, and that is not working so far.

Maybe there is much simpler solution for want I'm trying to accomplish. Can someone help me a bit?

Thanks!

Samall
  • 117
  • 9
  • 1
    Many StackOverflow users are quite firm in stating that regexes are the completely wrong tool for processing XML/HTML. More dedicated tools are the better choice. https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Yunnosch May 20 '18 at 12:21
  • I found a simpler solution: , I then need to figure out how to URLEncodedFormat the link. – Samall May 20 '18 at 12:35
  • 1
    @Yunnosch 's link is to one of the all time epic answers on Stackoverflow. Heed its advice. – James A Mohler May 20 '18 at 20:01
  • @Samall you only need to URLEncode the values of the query string parameters, not the whole link. – Adrian J. Moreno May 21 '18 at 04:50
  • You could also do this with javascript. Such that the source code has the target url as the href (for indexing purposes). But onClick gets in the middle and does the magic redirect for you. – Jules May 21 '18 at 16:09

0 Answers0