preg_replace to add new lines at end of closing html tags

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Walid
Forum Commoner
Posts: 33
Joined: Mon Mar 17, 2008 8:43 am

preg_replace to add new lines at end of closing html tags

Post by Walid »

Hi all,

Being as bad as I am with regular expressions, I'm hoping someone can help.

At the moment, I am doing this...

$HtmlTags = array("<tr>", "<li>", "<t", "</tr", "</tbody>", "</thead>", "</table>", etc.);
foreach($HtmlTags as $HtmlTag) $buffer = str_replace($HtmlTag, "\n".$HtmlTag, $buffer);

How can that be accomplished with preg_replace?

Thanks
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: preg_replace to add new lines at end of closing html tags

Post by onion2k »

HTML matching regex: http://haacked.com/archive/2004/10/25/u ... hhtml.aspx

Example of using it in PHP:

Code: Select all

   $line = "<table>  <tr valign='top'>  <td>Hello</td> </tr>  </table>";
    $line = preg_replace("@(</?\w+((\s+\w+(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)/?>)@", "$1\n", $line);
    $m = explode("\n",$line);
    foreach ($m as $l) {
        echo trim(htmlentities($l))."<br>";
    }
Walid
Forum Commoner
Posts: 33
Joined: Mon Mar 17, 2008 8:43 am

Re: preg_replace to add new lines at end of closing html tags

Post by Walid »

Worked like a charm. Thanks.
Post Reply