note 92371 added to tokenizer.examples

From: Date: Tue, 21 Jul 2009 19:15:41 +0000
Subject: note 92371 added to tokenizer.examples
Groups: php.notes 
Request: Send a blank email to php-notes+get-158558@lists.php.net to get a copy of this message
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 ---- Server IP: 69.147.83.197 Probable Submitter: 203.99.174.178 ---- Manual Page -- http://www.php.net/manual/en/tokenizer.examples.php Edit -- https://master.php.net/note/edit/92371 Del: integrated -- https://master.php.net/note/delete/92371/integrated Del: useless -- https://master.php.net/note/delete/92371/useless Del: bad code -- https://master.php.net/note/delete/92371/bad+code Del: spam -- https://master.php.net/note/delete/92371/spam Del: non-english -- https://master.php.net/note/delete/92371/non-english Del: in docs -- https://master.php.net/note/delete/92371/in+docs Del: other reasons-- https://master.php.net/note/delete/92371 Reject -- https://master.php.net/note/reject/92371 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#158558) next »