【发布时间】:2010-06-02 16:43:28
【问题描述】:
我使用 nicEdit 在我的 CMS 中写入 RTF 数据。问题是它会生成这样的字符串:
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>
所以我目前的解决方案是这样的:
- 我需要在字符串的开头/结尾处为
<br />修剪$data - 将所有包含 2 个或更多
<br/>的字符串替换为</p><p>(允许使用一个<br />)。 - 最后,在开头添加
<p>,在末尾添加</p>
到目前为止,我只有第 1 步和第 3 步。有人可以帮我完成第 2 步吗?
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;
}
谢谢!
ps:避免特定情况会更好。示例:“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;
}
【问题讨论】: