我有以下字符串
Brad Thorm signs for the <hash>All Blacks</hash>
标签之间可能不是“全黑”,它可能是任何东西。我需要解析此字符串,以便在遇到<hash></hash>
标记时:
寻找最干净的方法。
答案 0 :(得分:3)
将Chris的代码重写为函数并循环数组,这适用于提供的字符串中的多个哈希实例:
<cffunction name="renderHash" output="false" returnType="string">
<cfargument name="text" required="true" type="string" hint="The text to render." />
<cfset var strText = arguments.text />
<cfset var strHash = '' />
<cfset var arrMatches = reMatch("<hash>(.*?)</hash>", arguments.text) />
<cfloop array="#arrMatches#" index="i">
<cfset strHash = reReplace(i, "<hash>(.*?)</hash>", "\1") />
<cfset strHash = reReplace(strHash, "[[:space:]]", "", "ALL") />
<cfset strHash = "##" & strHash />
<cfset strText = replace(strText, i, strHash) />
</cfloop>
<cfreturn strText />
</cffunction>
传递字符串以转换为函数,您就完成了:
<cfset strText = '<hash>Brad Thorm</hash> signs for the <hash>All Blacks</hash>' />
<cfset strConverted = renderHash(strText) />
答案 1 :(得分:2)
可能有更简洁的方法来执行此操作,但这会将标记之间的任何文本转换为#hashtag,并处理字符串中的多个标记
<cfscript>
text = "<hash>Brad Thorm</hash> signs for the <hash>All Blacks</hash>";
matches = rematch("<hash>(.*?)</hash>", text);
for(match in matches) {
hashtag = reReplace(match, "<hash>(.*?)</hash>", "\1");
hashtag = reReplace(hashtag, "\W", "", "all");
hashtag = "##" & hashtag;
text = replace(text, match, hashtag);
}
writeoutput(text);
</cfscript>