更换新行以&lt p为H.;段落和以&lt; BR /&GT;标签 [英] Replace newlines with <p> paragraph and with <br /> tags
问题描述
所以我知道如何替换换行符在我的C#$ C $℃。但是,更换新行的&LT; BR /&GT;
标签并不总是非常正确的。
所以,我在想,做别人用什么样的策略?正确的方法我想是使用&LT; P&GT;
标记和&LT; BR /&GT;
标签。
下面是结果的一些例子,我想就搞定了。
如果没有换行我希望文本包装在&LT; P&GT;
标签。
这个文本中不包含换行
&LT; P&gt;这文本中不包含换行符&LT; / P&GT;
如果文本包含一个换行符我希望它由&LT更换; BR /&GT;
标签和包装在&LT; P&GT ;。
标签
这个文本包含
1换行
&LT; P&gt;这文本包含&LT; BR /&GT; 1换行符&其中; / P&GT;
如果有双换行符我想该块被包裹在&LT; P&GT;
标签
这是与双换行符末的文本。
这是一个没有换行符在结尾的文本。
&LT; P&GT; / P&gt;这带有双换行符在年底与其中的文本;
&LT; P&gt;这是没有换行符在年底℃的文本; / P&GT;
我可以写更多的例子/组合,但我想这是有些清楚我的意思。
在此先感谢。
下面是一个方法,你可以只用简单的字符串替换做到这一点:
字符串结果=&LT; P&gt;中+文本
.Replace(Environment.NewLine + Environment.NewLine,&所述; / P&GT;&其中; P&gt;中)
.Replace(Environment.NewLine,&LT; BR /&gt;中)
.Replace(&所述; / P&GT;&其中; P&gt;中,&所述; / P&gt;中+ Environment.NewLine +&其中; P&gt;中)+&所述; / P&gt;中;
请注意,您的文字必须是HTML转义第一否则,你可能会在跨站点脚本攻击的风险。 (注:即使使用&LT; pre&GT;
标签仍具有跨站点脚本的风险)。
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).
这篇关于更换新行以&lt p为H.;段落和以&lt; BR /&GT;标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!