我在我的CMS中使用NicEdit编写RTF数据。问题在于它会生成像这样的字符串:
由于这是一家新闻网站,我更喜欢最终的HTML是这样的:
hello first line<br><br />this is a second line<br />this is a 3rd line
由于这是一家新闻网站,我更喜欢最终的HTML是这样的:
<p>hello first line</p><p>this is a second line<br />this is a 3rd line</p>
我的目前解决方案是这样的:
- 我需要将 $data 开头和结尾的
<br />
去掉 - 将所有含有 2 个或以上
<br/>
的字符串替换为</p><p>
(可以有一个单独的<br />
)。 - 最后,在开头加上
<p>
,在结尾加上</p>
目前我只完成了步骤 1 和 3。能否有人帮我完成第二步呢?
function replace_br($data) {
# step 1
$data = trim($data,'<p>');
$data = trim($data,'</p>');
$data = trim($data,'<br />');
# step 2 ???
// preg_replace() ?
# step 3
$data = '<p>'.$data.'</p>';
return $data;
}
谢谢!
注:最好避免特定情况。例如:hello<br /><br /><br /><br /><br />too much space
- 这5个换行符应该转换为一个 "</p><p>
"。
最终解决方案(特别感谢kemp!)
function sanitize_content($data) {
$data = strip_tags($data,'<p>,<br>,<img>,<a>,<strong>,<u>,<em>,<blockquote>,<ol>,<ul>,<li>,<span>');
$data = trim($data,'<p>');
$data = trim($data,'</p>');
$data = trim($data,'<br />');
$data = preg_replace('#(?:<br\s*/?>\s*?){2,}#','</p><p>',$data);
$data = '<p>'.$data.'</p>';
return $data;
}
<br>
。 - Matteo Riva