【问题标题】:Removing space/line break between specific parts of a string删除字符串特定部分之间的空格/换行符
【发布时间】:2013-12-08 19:20:49
【问题描述】:

我正在尝试这样做,以便用户可以在他们的帖子中添加一个表格,这是我遇到的问题,在另一个函数中,我使用nl2br 来制作它,以便它自动添加换行符。虽然,表格是如何工作的,但所有换行符都会超出它,从而导致大量空间。我在下面提供了一张图片,以便您了解我的意思。我尝试使用\r\n\n,但我觉得我要么用错了,要么在这种情况下不起作用。

function markupDoc($post){
    //tables
    while(($post2 = preg_replace("/\[td]((?:(?!\[td\]).)+?)\[\/td\]/s", '<td>\\1</td>', $post)) !== $post){
        $post=$post2;
    }
    while(($post2 = preg_replace("/\[tr]((?:(?!\[tr\]).)+?)\[\/tr\]/s", "<tr>\\1</tr>", $post)) !== $post){
        $post=$post2;
    }
    while(($post2 = preg_replace("/\[thead]((?:(?!\[thead\]).)+?)\[\/thead\]/s", '<thead>\\1</thead>', $post)) !== $post){
        $post=$post2;
    }
    while(($post2 = preg_replace("/\[table]((?:(?!\[table\]).)+?)\[\/table\]/s", '<table class="table table-striped table-bordered">\\1</table>', $post)) !== $post){
        $post=$post2;
    }   
    return $post;
}

我要提交的字符串:

going to
[table]
    [thead]
        [td]test[/td]
        [td]test[/td]
        [td]moo[/td]
        [td]a[/td]
    [/thead]
    [tr]
        [td]test[/td]
        [td]moo[/td]
    [/tr]
    [tr]
        [td]test[/td]
        [td]test[/td]
        [td]moo[/td]
        [td]a[/td]
    [/tr]
[/table]

【问题讨论】:

  • 你能发布实际的原始输出而不是图像吗?
  • 它在表格上方返回&lt;br&gt; 标签,因为它不在一行上(我提交的字符串,它使用nl2br)。我添加了我正在使用的字符串。我用来测试的开发者网站就在这里:beta.projectdonut.me/docs/v/1385253660-documentation_Demo/… 如果有人想查看页面如何呈现它。
  • 您要删除&lt;br /&gt; 标签吗?还是所有的空白?
  • [table] 之间,我希望将其删除。您可以看到它是如何在呈现的表格上方添加 &lt;br&gt; 标记的,因为这就是表格的工作方式,而且我的字符串是多行的。
  • 它在表格的每一行之后添加&lt;br /&gt;标签。

标签: php regex preg-replace bbcode


【解决方案1】:

添加另一个功能来处理您帖子的不同部分。由于[table][\table] 之间的部分与其他部分明显不同,您应该执行以下操作:

function parsePost($post)
{
    $table_start = mb_strpos($post, '[table]');
    $table_end = mb_strpos($post, '[/table]', $table_start);
    $table_end += mb_strlen('[/table]');

    $output = nl2br(mb_substr($post, 0, $table_start));
    $output .= markupDoc(mb_substr($post, $table_start, $table_end - $table_start));
    $output .= nl2br(mb_substr($post, $table_end));
    return $output;
}

测试代码:http://ideone.com/sfRn33

【讨论】:

  • 删除了一些额外的空间,但不是全部。
  • 我忘了说:这甚至会支持多个表在一个字符串中吗?
  • 没有删除哪些空格?不,它不支持多个表,但不要指望我们为您编写代码 :) 您已经掌握了配方,现在您可以按照它进行操作(提示:将上面的代码放在一个循环中)。
  • 我打算这样做。它删除了大约 10% 的空间。
  • 也许您还应该将表外的$output 部分包装在trim() 函数中。
猜你喜欢
  • 2018-05-15
  • 2021-10-18
  • 2014-07-20
  • 1970-01-01
  • 2014-07-03
  • 2023-03-15
  • 2015-03-12
相关资源
最近更新 更多