所以我知道如何替换换行符在我的C#$ C $℃。但是,更换新行的< BR />
标签并不总是非常正确的。
所以,我在想,做别人用什么样的策略?正确的方法我想是使用< P>
标记和< BR />
标签。
下面是结果的一些例子,我想就搞定了。
如果没有换行我希望文本包装在< P>
标签。
这个文本中不包含换行
< P>这文本中不包含换行符< / P>
如果文本包含一个换行符我希望它由&LT更换; BR />
标签和包装在< P&GT ;。
标签
这个文本包含 1换行
< P>这文本包含< BR /> 1换行符&其中; / P>
如果有双换行符我想该块被包裹在< P>
标签
这是与双换行符末的文本。
这是一个没有换行符在结尾的文本。
< P> / P>这带有双换行符在年底与其中的文本;
< P>这是没有换行符在年底℃的文本; / P>
我可以写更多的例子/组合,但我想这是有些清楚我的意思。
在此先感谢。
解决方案下面是一个方法,你可以只用简单的字符串替换做到这一点:
字符串结果=< P>中+文本
.Replace(Environment.NewLine + Environment.NewLine,&所述; / P>&其中; P>中)
.Replace(Environment.NewLine,< BR />中)
.Replace(&所述; / P>&其中; P>中,&所述; / P>中+ Environment.NewLine +&其中; P>中)+&所述; / P>中;
请注意,您的文字必须是HTML转义第一否则,你可能会在跨站点脚本攻击的风险。 (注:即使使用< pre>
标签仍具有跨站点脚本的风险)。
So I know how to replace newlines in my C# code. But replacing a newline for a <br />
tag isn't always very correct.
So I was wondering what kind of strategy do others use? The correct way I guess would be to use <p>
tags and <br />
tags.
Here are some examples of the results I would like to get.
If there is no newline I want the text to wrapped in a <p>
tags.
This text contains no newlines
<p>This text contains no newlines</p>
If the text contains a newline I want it to be replaced by a <br />
tag and be wrapped in <p>
tags.
This text contains 1 newline
<p>This text contains<br /> 1 newline.</p>
If there are 'double newlines' I want that block to be wrapped in <p>
tags.
This is a text with 'double newlines' at the end.
This is a text with no newline at the end.
<p>This a text with 'double newlines at the end.</p>
<p>This is a text with no newline at the end.</p>
I could write more examples/combination but I guess it's somewhat clear what I mean.
Thanks in advance.
解决方案Here's a way you could do it using only simple string replacements:
string result = "<p>" + text
.Replace(Environment.NewLine + Environment.NewLine, "</p><p>")
.Replace(Environment.NewLine, "<br />")
.Replace("</p><p>", "</p>" + Environment.NewLine + "<p>") + "</p>";
Note that your text must be HTML-escaped first otherwise you could be at risk of cross-site scripting attacks. (Note: even using <pre>
tags still has a cross-site scripting risk).