我需要一个正则表达式来删除< FONT>的所有实例以及它里面可能包含的任何属性,例如< FONT size = 2 face = Verdana>及其结束标记< / FONT>.我回来的字符串,字体标记可以包含这些属性的任何属性和值的不同变体,并且html结构不一致.这是我作为字符串得到的一个例子:
<UL> <LI><FONT size=2 face=Verdana>random text<STRONG>random text</STRONG>random text<SPAN style="LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; FONT-SIZE: 11pt; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA"><SPAN style="mso-spacerun: yes"> </SPAN>random text</SPAN> </FONT></LI> <LI><FONT size=2 face=Verdana><FONT size=2 face=Verdana><STRONG>random text</STRONG></FONT></LI> <LI>random text</FONT></LI> <LI><FONT size=2 face=Verdana>random text</FONT></LI> <LI><FONT size=2 face=Verdana>random text</FONT></LI>
这就是我希望它在使用正则表达式后的样子:
<UL> <LI>random text<STRONG>random text</STRONG>random text<SPAN style="LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; FONT-SIZE: 11pt; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA"><SPAN style="mso-spacerun: yes"> </SPAN>random text</SPAN></LI> <LI><STRONG>random text</STRONG></LI> <LI>random text</LI> <LI>random text</LI> <LI>random text</LI>
我尝试了不同的变化,我已经能够删除< FONT部分但不删除它的属性,结尾>或结束标记< / FONT>
这是我正在使用的一个例子
loc.result = rereplace(arguments.htmlString,"\\<FONT[^*\\>","","ALL");
解决方法
如前所述,请不要使用REGEX.使用像JSoup这样的HTML解析器.
Download the JSoup jar file并将其保存在类路径的某个位置,然后使用以下函数(cfscript语法,使用Lucee测试,但应该适用于任何CFML引擎):
<cfscript> /** removes the given tag from the input html while keeping its contents */ function removeTag(input,tagname){ var Jsoup = createObject("java","org.jsoup.Jsoup"); var doc = Jsoup.parse(arguments.input); var body = doc.body().child(0); var tags = body.select(arguments.tagname); for (var tag in tags){ for (var attr in tag.attributes().asList()) tag.removeAttr(attr.getKey()); } var result = body.toString(); result = replace(result,"<#arguments.tagname#>","all"); result = replace(result,"</#arguments.tagname#>","all"); return result; } </cfscript>
cleanHtml = removeTag(inputHtml,"font");
<cfsavecontent variable="input"> <UL> <LI><FONT size=2 face=Verdana>random text 1<STRONG>random text 2</STRONG>random text 3<SPAN style="LINE-HEIGHT: 115%; FONT-FAMILY: 'Arial','sans-serif'; FONT-SIZE: 11pt; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA"><SPAN style="mso-spacerun: yes"> </SPAN>random text 4</SPAN> </FONT></LI> <LI><FONT size=2 face=Verdana><FONT size=2 face=Verdana><STRONG>random text 5</STRONG></FONT></LI> <LI>random text 5</FONT></LI> <LI><FONT size=2 face=Verdana>random text 6</FONT></LI> <LI><FONT size=2 face=Verdana>random text 7</FONT></LI> </cfsavecontent> <cfdump var="#{ output: removeTag(input,"font"),input: input }#">
输出如下: