    <?php
    function closeTags( &$html, $length = 20 ){
    	$htmlLength = strlen($html);
    	$unclosed = array();
    	$counter = 0;
    	$i=0;
    	while( ($i<$htmlLength) && ($counter<$length) ){
    		if( $html[$i]=="<" ){
    			$currentTag = "";
    			$i++;
    			if( ($i<$htmlLength) && ($html[$i]!="/") ){
    				while( ($i<$htmlLength) && ($html[$i]!=">") && ($html[$i]!="/") ){
    					$currentTag .= $html[$i];
    					$i++;
    				}
    				if( $html[$i] == "/" ){  
    					do{ $i++; } while( ($i<$htmlLength) && ($html[$i]!=">") );	
    				} else {
    					$currentTag = explode(" ", $currentTag);
    					$unclosed[] = $currentTag[0];
    				}
    			} elseif( $html[$i]=="/" ){
    				array_pop($unclosed);
    				do{ $i++; } while( ($i<$htmlLength) && ($html[$i]!=">") );
    			}
    		} else{
    			$counter++;	
    		}
    		$i++;
    	}
    	$result = substr($html, 0, $i-1);
    	$unclosed = array_reverse( $unclosed );
    	foreach( $unclosed as $tag ) $result .= '</'.$tag.'>';
    	print_r($result);
    }
    
    $html = "<div>123890<span>1234<img src='i.png' /></span>567890<div><div style='test' class='nice'>asfaasf";
    closeTags( $html, 20 );
    ?>
