简体   繁体   English

用<p>段和<br />标记替换换行符

[英]Replace newlines with <p> paragraph and with <br /> tags

So I know how to replace newlines in my C# code. 所以我知道如何在C#代码中替换换行符。 But replacing a newline for a <br /> tag isn't always very correct. 但是替换<br />标签的换行并不总是非常正确。

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. 我猜的正确方法是使用<p>标签和<br />标签。

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. 如果没有换行符,我希望文本包含在<p>标签中。

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. 如果文本包含换行符,我希望将其替换为<br />标记并包含在<p>标记中。

This text contains 本文包含
1 newline 1个换行符

<p>This text contains<br /> 1 newline.</p>

If there are 'double newlines' I want that block to be wrapped in <p> tags. 如果有“双重换行符”,我希望该块包含在<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>

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. 请注意,您的文本必须首先进行HTML转义,否则您可能会面临跨站点脚本攻击的风险。 (Note: even using <pre> tags still has a cross-site scripting risk). (注意:即使使用<pre>标签仍然存在跨站点脚本风险)。

You could just leave it alone and use CSS to render the breaks correctly. 您可以放下它并使用CSS正确渲染中断。 Here is a complicated example that is a kind of "pretty" replacement for the <pre> but you are using a <p> instead: 这是一个复杂的例子,它是<pre>的一种“漂亮”替代品,但你使用的是<p>:

<p style="padding: 1em; line-height: 1.1em; font-family: monospace; white-space: pre; overflow: auto; background-color: rgb(240,255,240); border: thin solid rgb(255,220,255);"> <p style =“padding:1em; line-height:1.1em; font-family:monospace; white-space:pre; overflow:auto; background-color:rgb(240,255,240); border:thin solid rgb(255,220,255); “>

Text goes here. 文字在这里。

</p> </ p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM