Twifty Twifty - 1 year ago 134
PHP Question

PHP remove terminal codes from string

While processing the input/output of a process created with

, I've been hit with the special terminal ANSI codes (
), aside from not finding a reference to what these particular codes are doing, they are really messing with my

Does PHP have a built in method for cleansing these types of strings? Or what would be the correct expression to use with
? Please note, I am dealing with non ascii characters, so stripping everything except... will not work.

Answer Source

Usually ANSI codes are introduced by an ESC (\033 aka \x1b), an open square bracket, then numbers (possibly repeated: *[32;40m) and terminated by a letter.

You can use something like #\\x1b[[][0-9]+(;[0-9]*)[A-Za-z]# to preg_replace them all to oblivion.

This works (just tested), even if definitely overkill:

$test = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $test);

I've also found this on GitHub, and this on SO.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download