如何保留<sup>whatever</sup>
&amp;我的coldfusion字符串中的<sub>whatever</sub>
个html标签,但摆脱了所有其他的html标签?
答案 0 :(得分:2)
虽然有很多方法可以在CF中运行正则表达式魔术,但我仍然更喜欢使用Java来浏览内容并捕获内容。
<!--- 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>
输出是:
Hello <sup>World</sup>
foo
<sub class="example">bar</sub>
答案 1 :(得分:0)
我认为你也可以在正则表达式替换中使用负向前瞻:
stripped_string = reReplaceNoCase(source_string, '<(?!/?su[bp]\b)[^>]+>', '', 'all' );