我创建了一个bbcode解析器,在输出时使用nl2br()。但是,为什么会有这样的结果呢
输入
[table][tr][td]1[/td]
[td]2[/td]
[/tr]
[tr][td]3[/td]
[td]4[/td]
[/tr]
[/table]
[ul]
[li]1[/li]
[li]2[/li]
[li]3[/li]
[/ul]
[ol]
[li]A[/li]
[li]B[/li]
[li]C[/li]
[/ol]输出
<br><br><br><br><br><br><table><tbody><tr><td>1</td>
<td>2</td>
</tr>
<tr><td>3</td>
<td>4</td>
</tr>
</tbody></table><br>
<br>
<ul><br>
<li>1</li><br>
<li>2</li><br>
<li>3</li><br>
</ul><br>
<br>
<ol><br>
<li>A</li><br>
<li>B</li><br>
<li>C</li><br>
</ol><br>我的php函数
function showBBcodes($text) {
$text = htmlspecialchars($text);
preg_match_all('#\[code\](.*?)\[/code]#is', $text, $stack);
// BBcode array
$find = array(
'~\[ul\](.*?)\[/ul\]~s',
'~\[li\](.*?)\[/li\]~s',
'~\[ol\](.*?)\[/ol\]~s',
'~\[table\](.*?)\[/table\]~s',
'~\[tr\](.*?)\[/tr\]~s',
'~\[td\](.*?)\[/td\]~s',
'~\[img\](.*?)\[/img\]~s',
'/\[img=(\d+)x(\d+)\](.*?)\[\/img\]/is'
);
// HTML tags to replace BBcode
$replace = array(
'<ul>$1</ul>',
'<li>$1</li>',
'<ol>$1</ol>',
'<table>$1</table>',
'<tr>$1</tr>',
'<td>$1</td>',
'<img src="$1" alt=""/>',
'<img width="$1" height="$2" src="$3" alt="" />'
);
$text = preg_replace($find,$replace,$text);
$text = nl2br($text);
foreach($stack[1] as $t) {
$text = preg_replace('#\[code\].*?\[/code]#is','<div class="code_box">'.$t.'</div>', $text,1);
}
return $text;
}我的测试:在table和/ table之间,显示六次\n所以之前table出现了六次
我怎么才能修复它呢?
我可以跳过在表li中不使用nl2br而在tr中使用吗??
或者任何人都可以给我更多的建议
谢谢。
发布于 2014-11-11 00:12:43
仅对标记li和td的内容使用nl2br
例如:
preg_match_all('#\[li\](.*?)\[/li]#is', $text, $stack);
foreach($stack[1] as $t) {
$text = str_replace($t, nl2br($t), $text);
}发布于 2014-11-11 00:28:41
我找到了答案:nl2br() in textarea with BBCode and HTML code
$formattedText = preg_replace("/(<[a-zA-Z0-9=\"\/\ ]+>)<br\ \/>/", "$1", nl2br($text));https://stackoverflow.com/questions/26847853
复制相似问题