I want to remove all the <br />
inside the table using PHP. I know I could use str_replace()
to remove <br />
. But it will remove all <br />
. I only want to remove <br />
between <table>
and </table>
. I have several tables in one string.
The html code is below. Also you can see this fiddle.
<p>Some text before table:</p><table cellpadding="0" cellspacing="0"><br /> <tbody><br /> <tr><br /> <td><br /> <p><strong>column1</strong></p> </td><br /> <td><br /> <p><strong>column2</strong></p> </td></tr><br /> <tr><br /> <td><br /> <p>1</p> </td><br /> <td><br /> <p>2</p> </td><br /> <br /> </tr><br /> </tbody><br /></table>
<p>Some text before table:</p><table cellpadding="0" cellspacing="0"><br /> <tbody><br /> <tr><br /> <td><br /> <p><strong>column1</strong></p> </td><br /> <td><br /> <p><strong>column2</strong></p> </td></tr><br /> <tr><br /> <td><br /> <p>1</p> </td><br /> <td><br /> <p>2</p> </td><br /> <br /> </tr><br /> </tbody><br /></table>
I tried the following way to do this, is this the best solution?
<?php
$input = '<p>Some text before table:</p><table cellpadding="0" cellspacing="0"><br /> <tbody><br /> <tr><br /> <td><br /> <p><strong>column1</strong></p> </td><br /> <td><br /> <p><strong>column2</strong></p> </td></tr><br /> <tr><br /> <td><br /> <p>1</p> </td><br /> <td><br /> <p>2</p> </td><br /> <br /> </tr><br /> </tbody><br /></table>
<p>Some text before table:</p><table cellpadding="0" cellspacing="0"><br /> <tbody><br /> <tr><br /> <td><br /> <p><strong>column1</strong></p> </td><br /> <td><br /> <p><strong>column2</strong></p> </td></tr><br /> <tr><br /> <td><br /> <p>1</p> </td><br /> <td><br /> <p>2</p> </td><br /> <br /> </tr><br /> </tbody><br /></table>';
$body = preg_replace_callback("~<table\b.*?/table>~si", "process_table", $input);
function process_table($match) {
return str_replace('<br />', '', $match[0]);
}
echo $body;
` tag in the table outside of the cells like in the example. This is the problem I guess. – Jakub Matczak Mar 19 '14 at 15:27
:) – Tularis Mar 19 '14 at 15:27
:) – Mike S. Mar 19 '14 at 15:29