问题
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