Invece di inzozzare l' OT magari lo scrivo qua' , servisse anche ad altri
In pratica capita di dover fare un parser per prendere testo , codice o quant' altro da un file o un testo rappresentante un file ... o una stringa con commenti ...
questa funzione semplicemente prende tutti i testi racchiusi tra apici singoli e/o doppi, li cambia nel loro hash md5, elimina a quel punto i commenti ( non importa se avevano stringhe al loro interno perche' sono stringhe di commenti, quindi vanno comunque tolte anche se hashate ) , poi riapplica agli hash residui, quelli non portati via dai commenti, il replace inverso , ed eccovi i testi con commenti o meno salvaguardati
spero sia utile a qualcuno
funzione
codice:
function removePHPComments( $text ) {
/**
* Function removePHPComments:
* removes all php comment from a string
* -------------------------------------
* @author Andrea Giammarchi
* @date 30/03/2005
* @compatibility PHP >= 4
*/
$string2md5 = create_function(
'$a,$b,&$d',
'$c = md5($b); $d[$c] = $a.$b.$a; return $c;'
);
$comments = $find = $replace = Array();
$text = preg_replace(
"/('|\")([^\a]*?)(\\1)/ie",
'$string2md5( "\\1", "\\2", $comments );',
$text
);
$text = preg_replace(
Array(
"/(\/\/)([^\\n]*|[^\\r]*)/",
"/(\/\*)([^\a]*?)(\*\/)/i"
),
"",
$text
);
foreach( $comments as $k => $v ) {
if( strpos( $text, $k ) !== false ) {
array_push( $find, $k );
array_push( $replace, $v );
}
}
return str_replace( $find, $replace, $text );
}
esempio
codice:
$text = "
/** osaksao o kds
jasd asodsoia dj a
jasoi d ojsadoiasj
*/
\"sadja wij wajdiw
// asd
wj aoid joaw
/*
lol
*/
ijd oai jd \"
// asjdijaoi wiojjo iwjd
'lol'
/** asjidj aowdiwaojwdiowdijawii*/
\"jiwjdiaj aidwwawida \"
";
echo '<pre>'.removePHPComments( $text ).'</pre>';
Nota Bene
e' studiata per commenti di tipo php, quindi
// per linea singola
e
/*
per multi linea
*/
basta modificare in modo ottimale le pregs per adattarsela per commenti tipo python o mysql
#
o altri che siano ...
insomma, una funzione per tante soluzioni, basta sapere cosa si vuole togliere