fork(7) download
  1. <?php
  2. function closeTags( &$html, $length = 20 ){
  3. $htmlLength = strlen($html);
  4. $unclosed = array();
  5. $counter = 0;
  6. $i=0;
  7. while( ($i<$htmlLength) && ($counter<$length) ){
  8. if( $html[$i]=="<" ){
  9. $currentTag = "";
  10. $i++;
  11. if( ($i<$htmlLength) && ($html[$i]!="/") ){
  12. while( ($i<$htmlLength) && ($html[$i]!=">") && ($html[$i]!="/") ){
  13. $currentTag .= $html[$i];
  14. $i++;
  15. }
  16. if( $html[$i] == "/" ){
  17. do{ $i++; } while( ($i<$htmlLength) && ($html[$i]!=">") );
  18. } else {
  19. $currentTag = explode(" ", $currentTag);
  20. $unclosed[] = $currentTag[0];
  21. }
  22. } elseif( $html[$i]=="/" ){
  23. array_pop($unclosed);
  24. do{ $i++; } while( ($i<$htmlLength) && ($html[$i]!=">") );
  25. }
  26. } else{
  27. $counter++;
  28. }
  29. $i++;
  30. }
  31. $result = substr($html, 0, $i-1);
  32. $unclosed = array_reverse( $unclosed );
  33. foreach( $unclosed as $tag ) $result .= '</'.$tag.'>';
  34. print_r($result);
  35. }
  36.  
  37. $html = "<div>123890<span>1234<img src='i.png' /></span>567890<div><div style='test' class='nice'>asfaasf";
  38. closeTags( $html, 20 );
  39. ?>
  40.  
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
    <div>123890<span>1234<img src='i.png' /></span>567890<div><div style='test' class='nice'>asf</div></div></div>