Reputation: 11
How can I keep <sup>whatever</sup>
& <sub>whatever</sub>
html tags in my coldfusion string but get rid of all other html tags?
Upvotes: 0
Views: 177
Reputation: 46
I think you could also use a negative lookahead in a regex replace like so:
stripped_string = reReplaceNoCase(source_string, '<(?!/?su[bp]\b)[^>]+>', '', 'all' );
Upvotes: 0
Reputation: 7833
Although there are many ways to run regex magic in CF, I still prefer some Java here to walk through content and capture stuff.
<!--- string with tags to strip --->
<cfsavecontent variable="stringToStrip">
<p class="something">
Hello <sup>World</sup>
</p>
<div>
<div style="border: 1px solid;">foo</div>
<sub class="example">bar</sub>
</div>
</cfsavecontent>
<!--- regex to capture all tag occurences --->
<cfset stripRegEx = "<[^>]+>">
<cfset result = createObject("java", "java.lang.StringBuilder").init()>
<cfset matcher = createObject("java", "java.util.regex.Pattern").compile(stripRegEx).matcher(stringToStrip)>
<cfset last = 0>
<cfloop condition="matcher.find()">
<!--- append content before next capture --->
<cfset result.append(
stringToStrip.substring(
last,
matcher.start()
)
)>
<!--- full tag capture --->
<cfset capture = matcher.group(
javaCast("int", 0)
)>
<!--- keep only sub/sup tags --->
<cfif reFindNoCase("</?su[bp]", capture)>
<cfset result.append(capture)>
</cfif>
<!--- continue at last cursor --->
<cfset last = matcher.end()>
</cfloop>
<!--- append remaining content --->
<cfset result.append(
stringToStrip.substring(last)
)>
<!--- final result --->
<cfset result = result.toString()>
<cfoutput>#result#</cfoutput>
Output is:
Hello <sup>World</sup>
foo
<sub class="example">bar</sub>
Upvotes: 3