Skip to content

Instantly share code, notes, and snippets.

@ralphschindler
Created October 1, 2012 17:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralphschindler/3813084 to your computer and use it in GitHub Desktop.
Save ralphschindler/3813084 to your computer and use it in GitHub Desktop.
<?php
function getFormattedOutput($string)
{
$tags = array(
'bold' => 1, 'dark' => 2, 'italic' => 3, 'underline' => 4, 'blink' => 5, 'reverse' => 7, 'concealed' => 8,
'black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37,
'bg_black' => 40, 'bg_red' => 41, 'bg_green' => 42, 'bg_yellow' => 43, 'bg_blue' => 44, 'bg_magenta' => 45, 'bg_cyan' => 46, 'bg_white' => 47
);
$matches = array();
$regex = '#(<(' . implode('|', array_keys($tags)) . ')\b[^>]*>)(.+?)</\2?>#si';
while (preg_match_all($regex, $string, $matches)) {
foreach ($matches[0] as $index => $matchFull) {
$replacement = '=START(' . $tags[$matches[2][$index]] . ')=' . $matches[3][$index] . '=END=';
$string = str_replace($matchFull, $replacement, $string);
}
}
$tokens = preg_split('#(=START\(\d+\)=|=END=?)#', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$codeStack = array();
foreach ($tokens as $tokenIndex => $token) {
if (strpos($token, '=START(') === 0) {
$codeStack[] = $codeNum = substr($token, 7, -2);
$tokens[$tokenIndex] = "\033[{$codeNum}m";
} elseif (strpos($token, '=END=') === 0) {
array_shift($codeStack);
$tokens[$tokenIndex] = "\033[" . (($codeStack) ? implode(',', $codeStack) : '0') . 'm';
}
}
return implode('', $tokens);
}
echo getFormattedOutput('<bg_blue><green><red>Foo</red> Bar</green></bg_blue>');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment