删除字符串中 bbcode 标签之间的空格

问题描述 投票:0回答:2

我需要删除字符串中相邻 BBCode 标签之间的所有空格,而不影响 BBCode 文本中的空格。输入是这样的:

*[ul]
    [li]List Item 1[/li]
    [li]List Item 2[/li]
[/ul]*

删除新行和标签后,它看起来像这样:

[ul] [li]List Item 1[/li] [li]List Item 2[/li] [/ul]

为了确保空格不会干扰代码,我需要删除命令之间的所有空格(

[ul]
[li]
[/ul]
[/li]
)。我怎样才能做到这一点?

php regex preg-replace whitespace bbcode
2个回答
1
投票

你可以做这样的事情,使用正则表达式和

preg_replace()

$text = preg_replace('/\[(.*?)\]\s*\[/', '[\1][', $text);

你可以想象这个正则表达式是如何工作的here.


1
投票

图案分解:

(?:^|\[[^]]+])  #match start of string or opening or closing bb tag
\K              #forget the matched characters so far
\s+             #match one or more whitespace characters 
(?=\[[^]]+]|$)  #lookahead for another opening or closing bb tag or the end of the string

代码:(演示

$bb = ' [ul]
    [li] List Item 1 [/li]
    [li] List Item 2 [/li]
[/ul] ';

var_export(
    preg_replace(
        '#(?:^|\[[^]]+])\K\s+(?=\[[^]]+]|$)#',
        '',
        $bb
    )
);

Regex 是,当然,一个 bbcode-ignorant 工具,它不知道它是否匹配合法的 bbcode 标签或只是看起来像 bbcode 标签的字符。为了提高严格性,您可以指定要列入白名单的标签。对于您的示例字符串,将执行以下操作:Demo

#(?:^|\[/?(?:ul|li)])\K\s+(?=\[/?(?:ul|li)]|$)#
© www.soinside.com 2019 - 2024. All rights reserved.