replace all line breaks between specific BBCode tags
I'm programming a wiki with BBCode-like editing syntax.
I want the user to be allowed to enter line breaks that resolve to <br>
tags.
Until here there's no problem occuring.
Now i also have the following lines, that should convert into a table:
[table]
[row]
[col]Column1[/col]
[col]Column2[/col]
[col]Column3[/col]
[/row]
[/table]
All those line breaks, that were entered when formatting the editable BBCode above are creating <br>
tags that are forced to be rendered in front of the html-table.
My goal is to remove all line breaks between [table]
and [/table]
in my parser function using php's preg_replace without breaking the possibility to enter normal text using newlines.
This is my parsing function so far:
function richtext($text)
{
$text = htmlspecialchars($text);
$expressions = array(
# Poor attempts
'/[table](rn*)|(r*)|(n*)[/table]/' => '',
'/[table]([^n]*?n+?)+?[/table]/' => '',
'/[table].*?(r+).*?[/table]/' => '',
# Line breaks
'/rn|r|n/' => '<br>'
);
foreach ($expressions as $pattern => $replacement)
{
$text = preg_replace($pattern, $replacement, $text);
}
return $text;
}
It would be great if you could also explain a bit what the regex is doing.
Style
First of all, you don't need the foreach
loop, preg_replace accepts mixed variables, eg arrays, see Example #2: http://www.php.net/manual/en/function.preg-replace.php
Answer
Use this regex to remove all line breaks between two tags (here table and row):
([table]([^rn]*))(rn)*([^rn]*[row])
The tricky part is to replace it (See also this: preg_replace() Only Specific Part Of String):
$result = preg_replace('/([table][^rn]*)(rn)*([^rn]*[row])/', '$1$4', $subject);
Instead of replacing with ''
, you replace it only the second group ( (rn)*
) with '$1$4'
.
Example
[table] // This will also work with multiple line breaks
[row]
[col]Column1[/col]
[col]Column2[/col]
[col]Column3[/col]
[/row]
[/table]
With the regex, this will output:
[table] [row]
[col]Column1[/col]
[col]Column2[/col]
[col]Column3[/col]
[/row]
[/table]
链接地址: http://www.djcxy.com/p/29876.html
上一篇: PHP当我有preg时如何做htmlspecialchars()
下一篇: 替换特定BBCode标记之间的所有换行符