Page 1 of 1

preg_replace to add new lines at end of closing html tags

Posted: Tue Mar 18, 2008 4:50 am
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

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

Posted: Tue Mar 18, 2008 6:16 am
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>";
    }

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

Posted: Tue Mar 18, 2008 7:41 am
by Walid
Worked like a charm. Thanks.