Best way to automatically remove comments from PHP code

I’d use tokenizer. Here’s my solution. It should work on both PHP 4 and 5: $fileStr = file_get_contents(‘path/to/file’); $newStr=””; $commentTokens = array(T_COMMENT); if (defined(‘T_DOC_COMMENT’)) { $commentTokens[] = T_DOC_COMMENT; // PHP 5 } if (defined(‘T_ML_COMMENT’)) { $commentTokens[] = T_ML_COMMENT; // PHP 4 } $tokens = token_get_all($fileStr); foreach ($tokens as $token) { if (is_array($token)) { if (in_array($token[0], … Read more

Remove trailing newline from the elements of a string list

You can either use a list comprehension my_list = [‘this\n’, ‘is\n’, ‘a\n’, ‘list\n’, ‘of\n’, ‘words\n’] stripped = [s.strip() for s in my_list] or alternatively use map(): stripped = list(map(str.strip, my_list)) In Python 2, map() directly returned a list, so you didn’t need the call to list. In Python 3, the list comprehension is more concise … Read more

Split by comma and strip whitespace in Python

Use list comprehension — simpler, and just as easy to read as a for loop. my_string = “blah, lots , of , spaces, here ” result = [x.strip() for x in my_string.split(‘,’)] # result is [“blah”, “lots”, “of”, “spaces”, “here”] See: Python docs on List Comprehension A good 2 second explanation of list comprehension.

How do I trim whitespace?

For whitespace on both sides, use str.strip: s = ” \t a string example\t ” s = s.strip() For whitespace on the right side, use str.rstrip: s = s.rstrip() For whitespace on the left side, use str.lstrip: s = s.lstrip() You can provide an argument to strip arbitrary characters to any of these functions, like … Read more

How to remove unused C/C++ symbols with GCC and ld?

For GCC, this is accomplished in two stages: First compile the data but tell the compiler to separate the code into separate sections within the translation unit. This will be done for functions, classes, and external variables by using the following two compiler flags: -fdata-sections -ffunction-sections Link the translation units together using the linker optimization … Read more