John Green
John Green

Reputation: 13435

Compare colored strings PHP

I am parsing a shell_exec for which I get a series of result strings, which I am comparing against data from other sources.

The input shell text contains ANSI colored text, which I can't seem to parse out. As a result, I can't do a basic string comparison, let alone an in_array as I'd planned.

I have attempted to use preg_replace with a number of PCRE classes (print, cntrl, etc) as well as simpler things like strcmp and strtolower, all to no avail.

I'm sure I'm missing something stupid, but I haven't been able to figure out which stupid thing I'm missing.

Upvotes: 2

Views: 68

Answers (2)

bishop
bishop

Reputation: 39374

Just throwing this out there. cat -vet is great for diagnostics, but sometimes it's great for dealing with non-porcelain output in a straight-forward way.

Give this a whirl:

$output = shell_exec("$cmd | cat -vet");
$output = preg_replace('/\^\[\[\d+m/', '', $output);

cat -vet is converting escape codes to individual printable characters, which you can then deal with as the actual characters themselves.

If your output has legitimate ^] and other similar sequences, this approach won't work. It's best to use PCRE that matches the actual escape codes as in @Amadan answer. But if you need something quick and dirty, this may work.

Upvotes: 1

Amadan
Amadan

Reputation: 198324

To weed out ANSI sequences:

preg_replace("/\e.*?[a-zA-Z]/", '', $str);

I believe you will always have the pattern of "escape, arguments, command" where the command is alphabetic, arguments numeric separated by colons if more than one.

Upvotes: 5

Related Questions