Replacing BB Code table tag using preg_replace

52 Views Asked by At

i have the below string.

$string="My Table
[table][tr][th]No.[/th][th]Content[/th][/tr][tr][td]1[/td][td]First[/td][/tr][tr][td]2[/td][td]Second[/td][/tr][tr][td]3[/td][td]Third[/td][/tr][/table]";

i want to replace this in to the following format.

$string="My Table<br><table><tr><th>No.</th><th>Content</th></tr><tr><td>1</td><td>First</td></tr><tr><td>2</td><td>Second</td></tr><tr><td>3</td><td>Third</td></tr></table>

I am trying to create a BBcode with preg_match. Please help.

I tried the following but it do not make the table tag mandatory. If some one do not close the table tag it makes issue to the whole page css.

    $string = preg_replace("#\[table\](.*?)\[\/table]#",'<table style=\'border:1px solid;\'>$1</table>',$Text);
    $Text = preg_replace("#\[tr\](.*?)\[\/tr]#is",'<tr style=\'border:1px solid;\'>$1</tr>',$Text);
    $Text = preg_replace("#\[td\](.*?)\[\/td]#is",'<td style=\'border:1px solid;padding:3px 3px 3px 3px;\'>$1</td>',$Text);
    $Text = preg_replace("#\[th\](.*?)\[\/th]#is",'<th style=\'border:1px solid;padding:3px 3px 3px 3px;\'>$1</th>',$Text);
1

There are 1 best solutions below

0
Timuran Bicer On

Actually, you just made a mistake, you need to use the same result in your next preg_replace.

Your variable $string is not reused after ...

Simply rename it to $Text