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
Exemples
Voici un exemple simple de scripts PHP utilisant le tokenizer qui lit un fichier PHP, supprime tous les commentaires de la source et affiche uniquement le code.
Exemple #1 Supprime les commentaires avec le tokenizer
<?php
/*
* T_ML_COMMENT n'existe pas en PHP 5.
* Les lignes suivantes le définisse afin de rendre
* compatible notre code.
*
* Ensuite, les 2 lignes définissent T_DOC_COMMENT uniquement pour PHP 5,
* que nous masquons en T_ML_COMMENT pour PHP 4.
*/
if (!defined('T_ML_COMMENT')) {
define('T_ML_COMMENT', T_COMMENT);
} else {
define('T_DOC_COMMENT', T_ML_COMMENT);
}
$source = file_get_contents('example.php');
$tokens = token_get_all($source);
foreach ($tokens as $token) {
if (is_string($token)) {
// un simple caractère token
echo $token;
} else {
// tableau token
list($id, $text) = $token;
switch ($id) {
case T_COMMENT:
case T_ML_COMMENT: // nous avons défini ceci
case T_DOC_COMMENT: // et ceci
// Aucune action sur les commentaires
break;
default:
// rien d'autre -> affiche "as is"
echo $text;
break;
}
}
}
?>
support at image-host-script dot com
21-Jul-2009 12:15
