1

我已经进行了广泛的谷歌搜索,但我似乎无法弄清楚。希望你能帮助我。

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

BB码

这是在我的留言板上控制 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 都链接到同一个地方——一个带有解决方案的线程现在在一个过期的链接上给出。但如果我错过了什么,请给我链接!

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

4

1 回答 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: ' '
}
于 2016-11-27T12:13:10.997 回答