问题
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 />
?
回答1:
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
回答2:
<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>
回答3:
Instead of replacing it with br I would use the ParagraphFormat function when displaying the values.
回答4:
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
回答5:
I actually prefer something like this:
<p>#REReplace(theParagraphText, "[#chr(10)#]+", "</p><p>", "ALL")#</p>
As it combines multiple line breaks into a single paragraph break.
来源:https://stackoverflow.com/questions/11330993/how-to-replace-crlf-with-br