ColdFusion 9:从字符串的特定部分中删除HTML标记

时间:2012-03-01 12:40:22

标签: regex coldfusion coldfusion-9

我一直在讨论这个问题很长一段时间。

我目前正在构建一个自定义BB-Code功能,作为工作项目的一部分。但是我不能让它在某一点上起作用:一个[代码]块。 使用 ColdFusion正则表达式,我想用<>替换< > 字符,但是仅在[code]块之间的HTML上。 那么,如何将正则表达式限制为[code]块之间的字符串部分。 提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

对于那些偶然发现这个问题并且也可以使用答案的人,我将提供一个在[code]块中解析HTML的示例。看起来有点凌乱:

<cfset contents = form.yourString />

<cfset substring1= "[code]" />
<cfset occurrences1 = ( Len(contents) - Len(Replace(contents,substring1,"","ALL"))) / Len(substring1) />
<cfset substring2= "[/code]" />
<cfset occurrences2 = ( Len(contents) - Len(Replace(contents,substring2,"","ALL"))) / Len(substring2) />

<cfif occurrences1 EQ occurrences2 AND occurrences1 GT 0 AND occurrences2 GT 0>
  <cfset loopinstance = occurrences1 />
<cfelse>
  <cfif occurrences1 LT occurrences2>
      <cfset loopinstance = occurrences1 />
  <cfelse>
      <cfset loopinstance = occurrences2 />
  </cfif>
</cfif>

<cfloop index="code_loop" from="1" to="#loopinstance#">
  <cfscript>
      // prepare variables //
      code_string = contents; 
      startpos = FindNoCase("[code]", code_string); 
      startpos = Evaluate(startpos + 6); // adjust the correct position of string in question 
      endpos   = FindNoCase("[/code]", code_string); 
      code_string = Mid(code_string, startpos, Evaluate(endpos - startpos)); // extract the string between code brackets 
      //** Replace-Codes are extensible depending on the used programming languages **//
      code_string = ReplaceNoCase(code_string, "<","&lt;", "ALL"); 
      code_string = ReplaceNoCase(code_string, ">","&gt;", "ALL"); 
      //** process conversion of [code] block **//
      startpos = FindNoCase("[code]", contents); // reevaluating the start and end positions for main string 
      startpos = Evaluate(startpos + 6); // adjust the correct position of form string 
      endpos   = FindNoCase("[/code]", contents); 
      contents = RemoveChars(contents, startpos, Evaluate(endpos - startpos)); // remove the extracted string 
      contents = Insert(code_string, contents, Evaluate(startpos - 1)); // insert the processed code block to the original position 
      contents = ReplaceNoCase(contents, "[code]", "[coded]", "ONE"); // "flagging" the processed [code] block as finished by adding a "d" 
      contents = ReplaceNoCase(contents, "[/code]", "[/coded]", "ONE"); // "flagging" the processed [code] block as finished by adding a "d" 
  </cfscript>
</cfloop>

<!--- This is the regex to turn a written [code] block into an escaped HTML block --->
<cfscript>
  contents = REReplaceNoCase(contents, "\[coded\](.*?)\[/coded\]", "<div id =""code_test"">Escaped Code: <br />\1</div>", "ALL"); 
</cfscript>

我希望这会帮助一些很难关注@David Faber帮助的人。

答案 1 :(得分:0)

我认为在ColdFusion中你必须迭代字符串,搜索“[code]”的出现。当您发现这种情况时,请读取字符串直到您点击“[/ code]”。取该字符串并执行replaceList替换字符。使用removeChars和insert函数将旧字符串替换为new。在此上下文中使用正则表达式的一个问题是CF函数REReplace不能用另一个模式替换模式,只能用字符串替换。