所以我know如何替换我的 C# 代码中的换行符。但是为 <br />
换行标签并不总是非常正确。
所以我想知道其他人使用什么样的策略?我猜正确的方法是使用 <p>
标签和 <br />
标签。
以下是我希望获得的结果的一些示例。
如果没有换行符,我希望将文本包裹在 <p>
中标签。
This text contains no newlines
<p>This text contains no newlines</p>
如果文本包含换行符,我希望将其替换为 <br />
标记并包裹在 <p>
中标签。
This text contains
1 newline
<p>This text contains<br /> 1 newline.</p>
如果有“双换行符”,我希望该 block 包含在 <p>
中标签。
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>
我可以写更多的例子/组合,但我想我的意思有点清楚。
提前致谢。
最佳答案
这是一种只使用简单的字符串替换就可以做到的方法:
string result = "<p>" + text
.Replace(Environment.NewLine + Environment.NewLine, "</p><p>")
.Replace(Environment.NewLine, "<br />")
.Replace("</p><p>", "</p>" + Environment.NewLine + "<p>") + "</p>";
请注意,您的文本必须首先进行 HTML 转义,否则您可能面临跨站点脚本攻击的风险。 (注意:即使使用 <pre>
标签仍然存在跨站点脚本风险)。
关于c# - 用 <p> 段落和 <br/> 标签替换换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2015563/