Reputation: 252
I have to challenges in regex.
How can i replace href="http://myserver.com"
If in my HTML
[Click here]. for example:
<a target="_blank" href="http://myserver.com" style="text-decoration: none; color: #fff;">Click here</a>
Replace With
<a target="_blank" href="##" style="text-decoration: none; color: #fff;">Click here</a>
In My HTML i have to search keyword ** ^mytag^ ** and replace with a value. currently im replacing one by one in loop.
Current Code:
#replace(MYHTMLcontent,"^mytag^","Name","All")#
Is there a way if i can search all my html keywords which is in my case something like ^keyword^
and add in add in structure.
Thanks
EDITED: Adding my new code what im working on im stuck if some-one can help me. it is replacing all links in my HTML.
<cffunction name="htmlurl" returntype="any" >
<cfargument name="aHTMLTemplate" required="yes" type="any" default="">
<cfargument name="addr" required="yes" type="any" default="http://url.com"> <!--- OR ## --->
<cfset regex = createObject("java", "java.util.regex.Pattern").compile('href=\"[^\"]+\"')>
<cfset result = createObject("java", "java.lang.StringBuilder").init()>
<cfset var htmlcont = arguments.aHTMLTemplate />
<cfset var toReplaceURL = arguments.avolurladdr />
<cfset matcher = regex.matcher(htmlcont)>
<cfset last = 0>
<cfloop condition="matcher.find()">
<cfset result.append(
htmlcont.substring(
last,
matcher.start()
)
)>
<cfset token = matcher.group(
javaCast("int", ( matcher.groupCount() gte 1 ? 1 : 0 ))
)>
<cfset token = ("<a href='"& toReplaceURL & "'")>
<cfset result.append(token)>
<cfset last = matcher.end()>
</cfloop>
<cfset result.append(htmlcont.substring(last))>
<cfset result = result.toString()>
<cfreturn result>
</cffunction>
Upvotes: 0
Views: 1034
Reputation: 478
Function:
<cffunction name="tmurlReplace" returntype="any" >
<cfargument name="HTMLCont" required="yes" type="any" default="">
<cfargument name="toreplaceURL" required="no" type="any" default="http://YOurURL.com">
<cfset var ehtml = arguments.HTMLCont>
<cfif refind("<a [^>]+>click here</a>",ehtml,1)>
<cfset ehtml = REReplace(ehtml, 'href=\"[^\"]+\"', "href='#toReplaceURL#'", "ALL") >
</cfif>
<cfreturn ehtml>
</cffunction>
Function Call:
`tmurlReplace(HTMLCont=MyHTMLCode)`
Hope It will help
Upvotes: 1
Reputation: 598
Well, I don't know anything about Coldfusion. But using pure Java, you could do something like this:
Question 1:
String replaced = "";
if(element.matches("<a [^>]+>Click here</a>") {
replaced = element.replaceAll("href=\"[^\"]+\"", "href=\"##\"");
}
The regex checks, if the given String is a link with Click here. Then, it replaces everything between "..." of href with ##.
Question 2:
String replaced = element.replaceAll("\^[^\^]+\^", "NAME");
The regex checks, if theres some ^anything^ anywhere and replaces that by NAME. If you're not familiar with regex: the part between [ and ] matches on anything which is not a ^. Looks kinda funny, though.
I hope this answer will help you.
Upvotes: 1