Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace CR+LF with <br />?

For example:

A user submits a form with a <textarea name="mytext" cols="35" rows="2"></textarea> and presses ENTER within it. How would I replace the CR-LF with a <br />?

like image 443
Seybsen Avatar asked Jul 04 '12 14:07

Seybsen


4 Answers

CF has a function for this called ParagraphFormat():

<cfset form.userText = paragraphFormat(form.usertext)/>

From the help docs -

Replaces characters in a string:

  • Single newline characters (CR/LF sequences) with spaces
  • Double newline characters with HTML paragraph tags (<p>)

It may do more than you want in that it also looks for double line breaks and adds <p> and </p> tags.

Ben also has an enhanced version (a UDF) called paragraph2 that would be easy to modify to get the exact affect you want. Here's the link:

http://www.cflib.org/udf/ParagraphFormat2

like image 156
Mark A Kruger Avatar answered Oct 10 '22 21:10

Mark A Kruger


<cfset localVars.ReturnString = REReplace(localVars.ReturnString, "\r\n|\n\r|\n|\r", "<br />", "all")>

You shouldn't hit \n\r naturally, but it can happen if it's being inserted by a dev who has forgotten the correct order.

That's a subset of a more generalised function to replace end of lines (EOL) chars with something else based on what you're doing (e.g. having to write out in Windows/Linux format, .ics files, html, cfheaders, etc)

<cffunction name="ReplaceEOL" access="public" output="false" returntype="string" hint="Replaces EOL codes with other characters">
    <cfargument name="String" required="true" type="string">
    <cfargument name="ReplaceWith" required="true" type="string">

    <cfreturn REReplace(Arguments.String, "\r\n|\n\r|\n|\r", Arguments.ReplaceWith, "all")>
</cffunction>
like image 26
nosilleg Avatar answered Oct 10 '22 20:10

nosilleg


Instead of replacing it with br I would use the ParagraphFormat function when displaying the values.

like image 38
jontro Avatar answered Oct 10 '22 22:10

jontro


You can use the paragraphFormat() function but sometimes a replace function helps you visualize what is actually happening.

An example: <cfset TheText=replace("#form.myText#",chr(13)&chr(10),"<br />","all")>

This replaces all carriage return-line feeds with an html line break

like image 36
Jim Butchart Avatar answered Oct 10 '22 20:10

Jim Butchart