Advertisement
Valleri

Semantic HTML

Sep 2nd, 2014
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.30 KB | None | 0 0
  1. <?php
  2. $html = 'html=<!doctype html>
  3. <html>
  4. <body>
  5. <header>
  6. <div style="color:red" id="nav" >
  7. Nav
  8. <div class="aside"  style="color:blue">
  9. Aside
  10. <div align = "left" class = "section" style = "color:blue">
  11.    <p class="header">
  12.        <span class="main">
  13.            Hi, I have class="main".
  14.        </span>
  15.    </p>
  16. </div> <!--  section-->
  17. </div> <!-- aside -->
  18. </div>  <!--nav -->
  19. Hello
  20. </header>
  21. </body>
  22. </html>';
  23. ;
  24. //$html = $_GET['html'];
  25. $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]+/';
  26. $closingRegex = '/\s*<\s*\/\s*div\s*>\s*<\s*!\s*-\s*-\s*(header|nav|main|aside|footer|section|article)\s*-\s*-\s*>\s*/';
  27.  
  28. $changed = array();
  29.  
  30. $lineByLine = explode(PHP_EOL, $html);
  31. $lineByLine = array_filter($lineByLine, function($val) {
  32.     if($val == "") {
  33.         return false;
  34.     }
  35.     return true;
  36. });
  37.  
  38. foreach ($lineByLine as &$line) {
  39.     preg_match($openingRegex, $line, $opening);
  40.     preg_match($closingRegex, $line, $closing);
  41.     //var_dump($opening);
  42.     if($opening) {
  43.         $line = str_replace($opening[2], '', $line);
  44.         $line = preg_replace("/\s*<\s*div/", "<" . $opening[3], $line);
  45.         $line = preg_replace("/\s+/", ' ', $line);
  46.         preg_match("/\s*<\s*" . $opening[3] ."\s*>/", $line, $res);
  47.         $changed[] = trim($opening[3]);
  48.         preg_match("/(\s+)>/", $line, $res2);
  49.         if($res) {
  50.             $line = preg_replace("/([\s]+)/", '', $line);
  51.         }
  52.         if($res2) {
  53.             $line = preg_replace("/([\s]+)(?=>)/", '', $line);
  54.         }
  55.     }
  56.     if($closing) {
  57.         if(count($changed) != 0) {
  58.             if($changed[count($changed) - 1] == $closing[1]) {
  59.                 preg_match("/\s+/", $line, $result);
  60.                 $line = str_replace($line, "</" . $closing[1] . ">", $line);
  61.                 $line = $result[0] . preg_replace("/([\s]+)/", '', $line);
  62.                 unset($changed[count($changed) - 1]);
  63.             } else {
  64.                 preg_match("/\s+/", $line, $result);
  65.                 $line = $result[0] . "</div>";
  66.             }
  67.         } else {
  68.             preg_match("/\s+/", $line, $result);
  69.             $line = $result[0] . "</div>";
  70.         }
  71.     }
  72. }
  73.  
  74. echo implode(PHP_EOL, $lineByLine);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement