Function to format custom tags 80% done [need help]

ok, im trying to program this custom function that will format data, according to if its tag (code, html, php and cmd wrapped by [ and ]).

Just that when there is a string that has more than one of those tags, lets say… php and html , it adds about 4 br tags on every line and it looks like im cuadruple spacing.

some help about how to avoid this? maybe using preg_split instead?