Split string into bbcode sections. PHP [duplicate]

爱⌒轻易说出口 提交于 2020-02-29 09:22:27

问题


I have a BBcode wysiwyg editor for only the basics styles bold, italic and underline. I need to take the stored data from it and use it to convent it into a PHPWord friendly array.

PHPWord works with something called textrun so to have many styles within a line you would simple do something like...

$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');

Im still completely unsure about how i do the nested tags.

So anyway here is what i need help doing. Turning this string below...

$string = "This is some text that contains [i]Italic[/i] and [b]bold[/b] text"

and turn it into an array like so

Array("This is some text that contains ","[i]Italic[/i]","and ","[b]bold[/b]","text");

Im a complete novice at regex and not even sure if you would use regex here.

My end goal is to end up with something like...

$PHPWordTextRun = new TextRun();
foreach($array as $line) {
    $PHPWordTextRun->addText($line['text'], $line['style']);
}

UPDATE:

So after testing around and playng with a couple of the answers i have come up with the following.

As suggested below i have tried the following.

$array = preg_split('/(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)/m', $txt, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

This is working to a degree but it did have plenty of blanks but fixed with PREG_SPLIT_NO_EMPTY but it doesnt support nested brackets.


回答1:


This expression might likely return what we wish to output, maybe with slight modifications, if not:

(.*?)(\[.+?\].+?\[\/.+?\])(.*?)|(.*)

Test

$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);

Demo

RegEx Circuit

jex.im visualizes regular expressions:



来源:https://stackoverflow.com/questions/56584583/split-string-into-bbcode-sections-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!