Codice PHP:
function count_t($tag$text) { 
    
$count 0
    for(
$i=0;$i<=strlen($text) - strlen($tag);$i++) { 
        
$s substr($text$istrlen($tag)); 
        if(
$s == $tag
            
$count++; 
    } 
     
    return 
$count


Codice PHP:
$tag = array( 
    
"[ URL ];[ /URL ]"
    
"[ i ];[ /i ]",
    
"[ B ];[ /B ]"
           
/* tag_aperto;tag_chiuso */ 
); 

$my_text "Il testo [b]è in grassetto";

foreach(
$tag as $t) { 
    
$g explode(";"$t); 
    
$diff count_t($g[0], $my_text) - count_t($g[1], $my_text);
    if(
$diff >= 1) {
        for(
$j 0;$j $diff;$j++)
                
$my_text .= $g[1];
    }


echo 
$my_text
lo script controlla quante volte è stato aperto un tag e quante volte è stato chiuso, se la differenza è maggiore o uguale ad 1, allora almeno un tag è stato lasciato aperto, e quindi li chiude in automatico