Reduced preg_match, preg_replace, and trim usage.
Added a second file handler to write on the fly instead of dumping it all into one variable then writing.
Replaced HTML BR check with using fgetss instead of fgets