Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $html = 'html=<!doctype html>
- <html>
- <body>
- <header>
- <div style="color:red" id="nav" >
- Nav
- <div class="aside" style="color:blue">
- Aside
- <div align = "left" class = "section" style = "color:blue">
- <p class="header">
- <span class="main">
- Hi, I have class="main".
- </span>
- </p>
- </div> <!-- section-->
- </div> <!-- aside -->
- </div> <!--nav -->
- Hello
- </header>
- </body>
- </html>';
- ;
- //$html = $_GET['html'];
- $openingRegex = '/\s*<\s*div\s+(.*?)\s*((?:id|class)\s*=\s*\"(\s*header\s*|\s*aside\s*|\s*footer\s*|\s*main\s*|\s*article\s*|\s*section\s*|\s*nav\s*)\")\s*[^\n]+/';
- $closingRegex = '/\s*<\s*\/\s*div\s*>\s*<\s*!\s*-\s*-\s*(header|nav|main|aside|footer|section|article)\s*-\s*-\s*>\s*/';
- $changed = array();
- $lineByLine = explode(PHP_EOL, $html);
- $lineByLine = array_filter($lineByLine, function($val) {
- if($val == "") {
- return false;
- }
- return true;
- });
- foreach ($lineByLine as &$line) {
- preg_match($openingRegex, $line, $opening);
- preg_match($closingRegex, $line, $closing);
- //var_dump($opening);
- if($opening) {
- $line = str_replace($opening[2], '', $line);
- $line = preg_replace("/\s*<\s*div/", "<" . $opening[3], $line);
- $line = preg_replace("/\s+/", ' ', $line);
- preg_match("/\s*<\s*" . $opening[3] ."\s*>/", $line, $res);
- $changed[] = trim($opening[3]);
- preg_match("/(\s+)>/", $line, $res2);
- if($res) {
- $line = preg_replace("/([\s]+)/", '', $line);
- }
- if($res2) {
- $line = preg_replace("/([\s]+)(?=>)/", '', $line);
- }
- }
- if($closing) {
- if(count($changed) != 0) {
- if($changed[count($changed) - 1] == $closing[1]) {
- preg_match("/\s+/", $line, $result);
- $line = str_replace($line, "</" . $closing[1] . ">", $line);
- $line = $result[0] . preg_replace("/([\s]+)/", '', $line);
- unset($changed[count($changed) - 1]);
- } else {
- preg_match("/\s+/", $line, $result);
- $line = $result[0] . "</div>";
- }
- } else {
- preg_match("/\s+/", $line, $result);
- $line = $result[0] . "</div>";
- }
- }
- }
- echo implode(PHP_EOL, $lineByLine);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement