Jump to content

Stripping terminal color codes in a CLI script


DWilliams

Recommended Posts

So long story short I have a fairly complicated PHP CLI program going here. Part of the input it receives from users naturally has Linux terminal codes. I want to log input from users however I don't want to output these colors to the logs because it will just end up as gibberish in the log file.

 

I have my colors defined as follows (and it works fine, I use it for outputting colored text at the terminal):

$C['NORMAL'] =		chr(27).'[0m';
$C['BOLD'] =		chr(27).'[1m';
$C['LIGHT_BLACK'] =	chr(27).'[1;30m';
$C['BLACK'] =		chr(27).'[0;30m';
$C['LIGHT_RED'] =	chr(27).'[1;31m';
$C['RED'] =		chr(27).'[0;31m';
$C['LIGHT_GREEN'] =	chr(27).'[1;32m';
$C['GREEN'] = 		chr(27).'[0;32m';
$C['LIGHT_YELLOW'] =	chr(27).'[1;33m';
$C['YELLOW'] =		chr(27).'[0;33m';
$C['LIGHT_BLUE'] =	chr(27).'[1;34m';
$C['BLUE'] =		chr(27).'[0;34m';
$C['LIGHT_MAGENTA'] =	chr(27).'[1;35m';
$C['MAGENTA'] =		chr(27).'[0;35m';
$C['LIGHT_CYAN'] =	chr(27).'[1;36m';
$C['CYAN'] =		chr(27).'[0;36m';
$C['WHITE'] =		chr(27).'[1;37m';
$C['GREY'] =		chr(27).'[0;37m';

 

Now, I figured it would be simple to write a function to strip colors from a string. Apparently I was wrong. I wrote the following:

function StripColors($str)
{
  global $C;
  foreach($C as $color)
    $str = str_replace($color, '', $str);
  return $str;
}

 

Unfortunately it appears to return the passed string completely unmodified. Help?

Try running some debugging:

 

function StripColors($str){
global $C;
foreach($C as $color){
	if(strpos($str, $color) === false)
		echo "Could not find {$color}.<br />";
	}else{
		echo "Found {$color} in string.<br />";
	}
}
}

 

Just see if it is even finding the colors.

Running that confirms that it isn't making a match on the color.

 

I thought the problem might be in that I used an associative array for colors, so I changed the foreach line to "foreach(array_values($C) as $color", but nothing appears to have changed.

 

Maybe the escape sequence in the colors (chr(27)) is messing up the match?

Bump. Perhaps I should have tried a more generic topic name as to not scare people away? I'm pretty sure the problem is something unrelated to terminal codes and CLI scripts. Is there some sort of "gotcha" with str_replace and escape characters?

I havent replied cause I havent played with color codes since I pulled my BBS in '94, did you try a straight escape?$C['NORMAL'] = "\\.'[0m'"; or maybe a preg using perl escape \e.

 

 

HTH

Teamatomic

I'll try that when I get home but it shouldn't make much of a difference, should it? The codes work fine when outputting, I just can't match on them.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.