Code snippet posted above is perfect enough, and I just wanted to put same code in a function that gets argument as code and returns the comments stripped code, so that it is easy for a beginner too, to copy and use this code.
<?
if (!defined('T_ML_COMMENT')) {
define('T_ML_COMMENT', T_COMMENT);
} else {
define('T_DOC_COMMENT', T_ML_COMMENT);
}
function strip_comments($source) {
$tokens = token_get_all($source);
$ret = "";
foreach ($tokens as $token) {
if (is_string($token)) {
$ret.= $token;
} else {
list($id, $text) = $token;
switch ($id) {
case T_COMMENT:
case T_ML_COMMENT: // we've defined this
case T_DOC_COMMENT: // and this
break;
default:
$ret.= $text;
break;
}
}
}
return trim(str_replace(array('<?','?>'),array('',''),$ret));
}
?>
1.Now using this function 'strip_comments' for passing code contained in some variable:
<?
$code = "
<?php
/* this is comment */
// this is also a comment
# me too, am also comment
echo "And I am some code...";
?>";
$code = strip_comments($code);
echo htmlspecialchars($code);
?>
Will result output as
<?
echo "And I am some code...";
?>
2.Loading from a php file:
<?
$code = file_get_contents("some_code_file.php");
$code = strip_comments($code);
echo htmlspecialchars($code);
?>
3. Loading a php file, stripping comments and saving it back
<?
$file = "some_code_file.php"
$code = file_get_contents($file);
$code = strip_comments($code);
$f = fopen($file,"w");
fwrite($f,$code);
fclose($f);
?>
regards
Ali Imran
Przykłady
Poniżej zamieszczony jest prosty przykład skryptu PHP, który używa tokenizera. Skrypt wczytuje plik PHP, usuwa wszystkie komentarze z kodu źródłowego i wyświetla sam czysty kod.
Przykład #1 Usuwanie komentarzy za pomocą tokenizera
<?php
/* T_ML_COMMENT nie istnieje w PHP 5.
* Następujące trzy linie definiują tę stałą, by zachować kompatybilność
* wsteczną.
*
* Kolejne dwie linie definiują istniejącą tylko w PHP 5 stałą
* T_DOC_COMMENT, którą w PHP 4 podmienimy jako T_ML_COMMENT.
*/
if (!defined('T_ML_COMMENT')) {
define('T_ML_COMMENT', T_COMMENT);
} else {
define('T_DOC_COMMENT', T_ML_COMMENT);
}
$kod = file_get_contents("jakisplik.php");
$tokeny = token_get_all($kod);
foreach ($tokeny as $token) {
if (is_string($token)) {
// prosty token jednoznakowy
echo $token;
} else {
// tablica definiująca token
list($id, $tekst) = $token;
switch ($id) {
case T_COMMENT:
case T_ML_COMMENT: // to zdefiniowaliśmy
case T_DOC_COMMENT: // to też
// brak akcji dla komentarzy
break;
default:
// wszystko inne -> wyświetl "takie, jakie jest"
echo $tekst;
break;
}
}
}
?>
support at image-host-script dot com
21-Jul-2009 12:15
