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\](\r\n*)|(\r*)|(\n*)\[\/table\]/' => '',
        '/\[table\]([^\n]*?\n+?)+?\[\/table\]/' => '',
        '/\[table\].*?(\r+).*?\[\/table\]/' => '',
        # Line breaks
        '/\r\n|\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, e.g. 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\]([^\r\n]*))(\r\n)*([^\r\n]*\[row\])

The tricky part is to replace it (See also this: preg_replace() Only Specific Part Of String):

$result = preg_replace('/(\[table\][^\r\n]*)(\r\n)*([^\r\n]*\[row\])/', '$1$4', $subject);

Instead of replacing with '', you replace it only the second group ((\r\n)*) 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] 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top