Skip to content

Instantly share code, notes, and snippets.

@ashleyhindle
Created October 11, 2016 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashleyhindle/9ed6863f9d7d105779e7130cbf518330 to your computer and use it in GitHub Desktop.
Save ashleyhindle/9ed6863f9d7d105779e7130cbf518330 to your computer and use it in GitHub Desktop.
Highlights words piped through STDIN
#!/usr/bin/env php
<?php
if (empty($argv[1]) || strpos($argv[1], '-h') !== false) {
die('Pass highlights as arguments (case sensitive): echo "cheese is nice" | highlight cheese nice' . PHP_EOL);
}
// Lovingly borrowed from http://blog.lenss.nl/2012/05/adding-colors-to-php-cli-script-output/ SHOUTOUT
$colors = [
'green' => '0;32',
'yellow' => '1;33',
'blue' => '0;34',
'cyan' => '0;36',
'purple' => '0;35',
'red' => '0;31',
'brown' => '0;33',
'light_gray' => '0;37',
'dark_gray' => '1;30',
'light_red' => '1;31',
'light_green' => '1;32',
'light_blue' => '1;34',
'light_purple' => '1;35',
'light_cyan' => '1;36',
'white' => '1;37',
];
array_shift($argv);
$colorsToUse = count($argv);
$highlight = $argv;
$replacements = [];
foreach ($highlight as $word) {
$colorCode = $colors[array_keys($colors)[count($replacements)]];
$replacements[] = "\033[{$colorCode}m{$word}\033[0m"; // TODO: Reuse colors when we're out if somebody highlights > count($colors)
}
while(!feof(STDIN)) {
//TODO: Replace fgets with fread or similar so it's faster. Also, what if it's just an insanely long line?
$line = fgets(STDIN);
$line = str_replace($highlight, $replacements, $line);
echo $line;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment