我有一个BBcode wysiwyg编辑器,仅适用于粗体,斜体和下划线的基本样式。我需要从中获取存储的数据并将其用于将其保存到PHPWord友好数组中。
PHPWord与textrun一起使用,因此在一行中具有多种样式,您只需执行以下操作即可...
$PHPWordTextRun = new TextRun();
$PHPWordTextRun->addText('This is some text that contains ', 'NORMAL');
$PHPWordTextRun->addText('Italic ', 'ITALIC');
$PHPWordTextRun->addText(' and ', 'NORMAL');
$PHPWordTextRun->addText('bold', 'BOLD');
$PHPWordTextRun->addText('text', 'NORMAL');
我仍然完全不确定如何处理嵌套标签。
所以无论如何,这就是我需要帮助的地方。将此字符串放在下面...
$string = "This is some text that contains [i]Italic[/i] and [b]bold[/b] text"
并把它变成这样的数组
Array("This is some text that contains ","[i]Italic[/i]","and ","[b]bold[/b]","text");
我是regex的一个新手,甚至不确定是否要在这里使用regex。
我的最终目标是得到类似...
$PHPWordTextRun = new TextRun();
foreach($array as $line) {
$PHPWordTextRun->addText($line['text'], $line['style']);
}
更新:
因此,在测试了几个答案之后,我提出了以下答案。
如下所示,我尝试了以下方法。
$array = preg_split('/(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)/m', $txt, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
这在一定程度上是可行的,但确实有很多空白,但已使用PREG_SPLIT_NO_EMPTY进行了修复,但不支持嵌套的括号。
答案 0 :(得分:0)
此表达式可能会返回我们希望输出的内容,如果没有的话,可能会稍作修改:
(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)
$re = '/(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)/m';
$str = 'This is some text that contains [i]Italic[/i] and [b]bold[/b] text This is some text that contains [i]Italic[/i] and [b]bold[/b] text This is some text that contains [i]Italic[/i] and [b]bold[/b] text';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
jex.im可视化正则表达式: