将URLEncodedFormat与REReplace一起使用

时间:2010-04-12 17:42:36

标签: regex coldfusion

我正在尝试更改以下行的实例:

URL: http://www.google.com/?s= test

URL: <a href="http://www.google.com/?s=%20test">http://www.google.com/?s= test</a>

请注意,锚网址是网址编码的

我设法使用一个非常简单的正则表达式来解析URL部分:

<cfset getFacts.fact_details = REReplace(getFacts.fact_details,
"URL:[ ]*([^#chr(13)##chr(10)#]+)",
"URL: <a href='\1' target='_blank'>\1</a>", "ALL")><!--- URL to newline into link --->

只抓取“URL:”之后的内容直到换行符

如何将URLEncodedFormat与此结合使用,或者使用所有正则表达式?

2 个答案:

答案 0 :(得分:4)

您需要在单独的步骤中执行此操作,因为您无法在RegEx中使用函数调用。

首先,使用REFind获取URL位置。你已经有了正则表达式。

现在,使用mid()来抓取URL。将其存储在变量中以进行操作。删除URL:part,然后执行URLEncodedFormat()调用。我将它存储在一个单独的var中,因此您可以显示最初输入的URL。使用这两个变量来创建替换(链接)字符串。

现在,您可以使用left()和right()创建结果,以提取URL之前和之后的内容,并在它们之间插入替换字符串。

PITA的种类,但确实存在。

答案 1 :(得分:0)

为什么要使用正则表达式?有很好的列表功能完全符合这项工作。

<cfoutput>
  <cfset BrokenUrl = "http://www.google.com/?s= test&f=%20foo%20&g&g/=/">
  <cfset FixedUrl  = FixUnencodedUrl(BrokenUrl)>
  #HTMLEditFormat(FixedUrl)#
  <!--- prints: http://www.google.com/?s=%20test&f=%20foo%20&g=&g%2F=%2F --->
</cfoutput>

<cffunction name="FixUnencodedUrl" returntype="string" access="public">
  <cfargument name="UrlStr" type="string" required="yes">

  <cfset var UrlPath  = ListFirst(UrlStr, "?")>
  <cfset var UrlQuery = ListRest(UrlStr, "?")>
  <cfset var NewQuery = "">
  <cfset var part     = "">
  <cfset var name     = "">
  <cfset var value    = "">

  <cfloop list="#UrlQuery#" index="part" delimiters="&">
    <cfset name  = ListFirst(part, "=")>
    <cfset value = ListRest(part, "=")>
    <!--- only encode if not already encoded --->
    <cfif name eq URLDecode(name)>
      <cfset name = URLEncodedFormat(name)>
    </cfif>
    <cfif value eq URLDecode(value)>
      <cfset value = URLEncodedFormat(value)>
    </cfif>
    <!--- build new, encoded query string --->
    <cfset NewQuery = ListAppend(NewQuery, "#name#=#value#", "&")>
  </cfloop>

  <cfreturn ListAppend(UrlPath, NewQuery, "?")>
</cffunction>