$t = ltrim(preg_replace('/\s*[#;].*$/m', '', $t));
Should work. Removes all comments, making sure not to leave any blank lines where comments used to be. Also kills whitespace before comments, but that can be changed (\s
to \n
) if you don't want that.
Edit: Just saw the note regarding removing blank lines. The following should remove both comments and blank lines:
$t = ltrim(preg_replace('/(\s*[#;].*$)|(^\s*)/m', '', $t));
Untested, but the second condition should catch blank (only whitespace) lines. The ltrim
is still necessary to remove any whitespace that a leading comment may have caused. Possibly could catch that as part of the regexp, but I think it's less complex with an ltrim
.
Edit Again: Actually the above would remove all leading whitespace on each line. If that's a problem, you could fix it with:
$t = ltrim(preg_replace('/(\s*[#;].*$)|(^\s*\n)/m', '', $t));