Problem with replacing newline characters with

in php

WBOY
Release: 2016-08-18 09:16:33
Original
2322 people have browsed it

<p>用nl2br处理了从数据库里取的数据,不想使用<br>换行,想使用<p>分段。<br>网上找到的方法:

<code>$content = '<p>'.str_replace("<br />","</p><p>",$content).'</p>';
</code>
Copy after login
Copy after login
<p>但是我的数据里还有别的一些标签,转换的时候就会有问题。<br>比如我有这样一段数据:

<code>blahblah<br />
<pre class="brush:php;toolbar:false"><code><br />
blahblah<br />
blahblah<br />
</code>
Copy after login
Copy after login
<p>就会变成

<code><p>blahblah</p><p>
<pre class="brush:php;toolbar:false"><code></p><p>
blahblah</p><p>
</code>

Copy after login
Copy after login
<p>这样我的<pre class="brush:php;toolbar:false">&lt;code&gt;&lt;/code&gt;</pre>代码块就被隔断了。<br>有没有什么办法不替换<pre class="brush:php;toolbar:false">&lt;code&gt;&lt;/code&gt;</pre>里的换行?

回复内容:

<p>用nl2br处理了从数据库里取的数据,不想使用<br>换行,想使用<p>分段。<br>网上找到的方法:

<code>$content = '<p>'.str_replace("<br />","</p><p>",$content).'</p>';
</code>
Copy after login
Copy after login
<p>但是我的数据里还有别的一些标签,转换的时候就会有问题。<br>比如我有这样一段数据:

<code>blahblah<br />
<pre class="brush:php;toolbar:false"><code><br />
blahblah<br />
blahblah<br />
</code>
Copy after login
Copy after login
<p>就会变成

<code><p>blahblah</p><p>
<pre class="brush:php;toolbar:false"><code></p><p>
blahblah</p><p>
</code>

Copy after login
Copy after login
<p>这样我的<pre class="brush:php;toolbar:false">&lt;code&gt;&lt;/code&gt;</pre>代码块就被隔断了。<br>有没有什么办法不替换<pre class="brush:php;toolbar:false">&lt;code&gt;&lt;/code&gt;</pre>里的换行?

<code class="php">echo preg_replace('#([a-zA-Z]*)<br\s*\/>#', "<p>$1</p>", "blahblah<br />
<pre class="brush:php;toolbar:false"><code><br />
blahblah<br />
blahblah<br />
</code>
");
Copy after login

<p>p和br都是标签,没有什么转换的必要,你想要<p>的效果也就是为了好看点,所以直接用css就行了,别折腾PHP了。例如

<code>p br {margin-bottom: 1em;}
p pre br {margin-bottom: 0;}</code>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template