note 91065 added to function.php-strip-whitespace
| From: | TK at osu1 dot php dot net | Date: | Sat, 23 May 2009 01:07:43 +0000 |
| Subject: | note 91065 added to function.php-strip-whitespace | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-155901@lists.php.net to get a copy of this message | ||
I was looking earlier for a way to strip php comments from my source files but didn't come up
with much. I wrote the following function to do the trick using the tokenizer. I've tested in
on an entire phpMyAdmin install and it worked fine afterward... so it should be good to go. You may
also specify any number of tokens to strip such as T_WHITESPACE rather the default of T_COMMENT and
T_DOC_COMMENT.
Hopefully someone finds it useful.
<?php
function strip_tokens($code) {
$args = func_get_args();
$arg_count = count($args);
// if no tokens to strip have been specified then strip comments by default
if( $arg_count === 1 ) {
$args[1] = T_COMMENT;
$args[2] = T_DOC_COMMENT;
}
// build a keyed array of tokens to strip
for( $i = 1; $i < $arg_count; ++$i )
$strip[ $args[$i] ] = true;
// set a keyed array of newline characters used to preserve line numbering
$newlines = array("\n" => true, "\r" => true);
$tokens = token_get_all($code);
reset($tokens);
$return = '';
$token = current($tokens);
while( $token ) {
if( !is_array($token) )
$return.= $token;
elseif( !isset($strip[ $token[0] ]) )
$return.= $token[1];
else {
// return only the token's newline characters to preserve line numbering
for( $i = 0, $token_length = strlen($token[1]); $i < $token_length; ++$i )
if( isset($newlines[ $token[1][$i] ]) )
$return.= $token[1][$i];
}
$token = next($tokens);
} // while more tokens
return $return;
} // function
?>
----
Server IP: 208.69.120.35
Probable Submitter: 24.67.132.88
----
Manual Page -- http://www.php.net/manual/en/function.php-strip-whitespace.php
Edit -- https://master.php.net/note/edit/91065
Del: integrated -- https://master.php.net/note/delete/91065/integrated
Del: useless -- https://master.php.net/note/delete/91065/useless
Del: bad code -- https://master.php.net/note/delete/91065/bad+code
Del: spam -- https://master.php.net/note/delete/91065/spam
Del: non-english -- https://master.php.net/note/delete/91065/non-english
Del: in docs -- https://master.php.net/note/delete/91065/in+docs
Del: other reasons-- https://master.php.net/note/delete/91065
Reject -- https://master.php.net/note/reject/91065
Search -- https://master.php.net/manage/user-notes.php