Using URLEncodedFormat with REReplace

I am trying to change the instances of the following line:

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

      

to

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

      

note that the anchor url is url encoded

I was able to parse the url with a simple simple expression:

<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 --->

      

which just grabs the content after "url:" to a new line

How can I enable URLEncodedFormat with this or use the whole regex?

+2


source to share


2 answers


You will need to do this in separate steps as you cannot use function calls in RegEx.

First enter the url using REFind. You already have a regular expression.

Now, use mid () to grab only the URL. Store this in a variable for manipulation. Remove the URL: part and then call URLEncodedFormat (). I would keep this in a separate var so that you can display the url that was originally entered. Use these two vars to create your replacement (link).



Now you can create your result using left () and right () to extract what came before and after your URL and insert a replacement string in between.

PITA view, but it is there.

+4


source


Why use a regular expression? There are some nice list functions that are great for the job.



<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>

      

0


source







All Articles