BBcode表引起的空间过大(PHP)

问题描述 投票:1回答:1

我做了大量的谷歌搜索,我似乎无法搞清楚。希望你能帮助我。

我正在编写留言板。系统会根据回复过滤HTML,并强制我的成员使用标准BBcode。所有基本的BB代码都运行顺畅,但是我遇到了我的表格代码。

BBcode

这是控制留言板上BBcode的脚本。这非常简单直接。我只关心[table] [tr]和[td],但我包含了[b],这样你就会明白该函数只处理我正在使用的三个代码。

function BBcode($original_string) {

$find = array(
'/\[b\](.*?)\[\/b\]/is',
'/\[table\](.*?)\[\/table\]/is',
'/\[tr\](.*?)\[\/tr\]/is',
'/\[td\](.*?)\[\/td\]/is'
);

$replace = array(
'<b>$1</b>',
'<table border="1" cellpadding="5">$1</table>',
'<tr>$1</tr>',
'<td>$1</td>
);

$new_string = preg_replace ($find, $replace, $original_string);

return $new_string;

}

因此,如果一个成员想在消息板上的响应中使用表BBcode代码,他们可能会输入如下内容:

[table]

[tr]
[td]Cell 1[/td]
[td]Cell 2[/td]
[td]Cell 3[/td]
[/tr]

[tr]
[td]x[/td]
[td]y[/td]
[td]z[/td]
[/tr]

[/table]

哪个好极了!这按计划工作。

问题

虽然它有一个主要缺陷 - 如果一个成员使用上面提供的BBcode提交表格,nl2br会添加一大堆无用的空格。你可以在这里看到我的意思:

(想象一下每增加一个TR会有多糟糕)

但是,如果用户发布他们的评论,如下所示:

[table] [tr] [td]Cell 1[/td] [td]Cell 2[/td] [td]Cell 3[/td] [/tr] [tr] [td]x[/td] [td]y[/td] [td]z[/td] [/tr] [/table]

他们发布的评论看起来不错

我已经尝试过的

我已经发现这种情况正在发生,因为我在这些评论中使用了nl2br。目前,它在BBcode功能运行之前添加了BR标签。我尝试在BBcode之后移动nl2br,但那不起作用。

接下来,我回到BBcode函数并尝试在数组中执行str_replace。

function BBcode($original_string) {

$find = array(
'/\[b\](.*?)\[\/b\]/is',
'/\[table\](.*?)\[\/table\]/is',
'/\[tr\](.*?)\[\/tr\]/is',
'/\[td\](.*?)\[\/td\]/is'
);

$replace = array(
'<b>$1</b>',
'<table border="1" cellpadding="5">' .print str_replace("<br />", "", "$1"). '</table>',
'<tr>$1</tr>',
'<td>$1</td>
);

$new_string = preg_replace ($find, $replace, $original_string);

return $new_string;

}

我还试图用无数其他方式写出这一行,例如:

'<table border="1" cellpadding="5">' .str_replace("<br />", "", "$1"). '</table>',
'<table border="1" cellpadding="5">' .str_replace("<br />", "", "$1"). '$1</table>',
'<table border="1" cellpadding="5">' .str_replace("<br />", "", "$1"). '$1</table>',
'<table border="1" cellpadding="5">' . $thing = str_replace("<br />", "", "$1"); . '$thing</table>',
'<table border="1" cellpadding="5">' . $thing = str_replace("<br />", "", "$1") . '$thing</table>',
'<table border="1" cellpadding="5">' . print str_replace("<br />", "", $1); . '</table>',
etc

基本上,我想要做的是替换[table]代码中找到的所有BR标签。我该怎么做呢?我究竟做错了什么?我应该改变方法吗?

如果这个问题在其他地方得到解答,我会提前道歉。我在其他论坛上看到至少有三个人有同样的问题,但是OP都链接到同一个地方 - 现在在过期链接上给出解决方案的线程。但如果我错过了什么,请链接我!

如果您有任何问题,请询问!

php html-table str-replace bbcode nl2br
1个回答
0
投票

当我遇到这个问题时,我所做的就是隐藏br/

我将表设置在自定义div

$replace = array(
    '<div class="tablepost"><table border="1" cellpadding="5">' .print str_replace("<br />", "", "$1"). '</table></div>',

然后添加了这个css技巧:

.tablepost > br {
  content: ' '
}
© www.soinside.com 2019 - 2024. All rights reserved.