|a|simple|table| without Textile

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
tom_jones
Forum Newbie
Posts: 3
Joined: Wed Oct 26, 2005 2:59 pm

|a|simple|table| without Textile

Post by tom_jones »

Hello everybody,

I'd like to replace this...

|a|table|row|
|a|table|row|

...with this...

<table>
<tr><td>a</td><td>table</td><td>row</td></tr>
<tr><td>a</td><td>table</td><td>row</td></tr>
</table>

I'd use Textile but this is the only thing I need it for-- overkill.

Any ideas?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Unlessthere's only ever two rows, with 3 columns it's more then just a single regex...

Code: Select all

$string = "|a|table|row|
|a|table|row|
";

function tabularize($input)
{
    $ret = '<table>';

    $rows = explode("\n", $input);
    foreach ($rows as $col)
    {
        $cells = explode('|', $col)
        $ret .= '<tr>';
        foreach ($cells as $value)
        {
             $ret .= '<td>'.$value.'</td>';
        }
        $ret .= '</tr>';
    }

    $ret .= '</table>';

    return $ret;
}
That's no regex at all :P

Maybe there's a better way but that just came naturally :)
tom_jones
Forum Newbie
Posts: 3
Joined: Wed Oct 26, 2005 2:59 pm

Post by tom_jones »

Wow, that was fast-- Thanks, d11wtq!
Post Reply