composer require weew/console-formatter
This package allows you to format text for terminal, using very simple and html like syntax. You will be able to change text color, text background and text format.
This package has not been tested on windows and I do not intend to do so. Contributions for windows support are highly appreciated.
Before you'll be able to use styles, you must created them first.
$formatter = new ConsoleFormatter();
$style = (new ConsoleStyle('alert'))
->setColor(ConsoleColor::WHITE)
->setBackground(ConsoleBackground::RED)
->setFormat([ConsoleFormat::BOLD, ConsoleFormat::UNDERLINE]);
$formatter->addStyle($style);
// or
$formatter->style('alert')
->setColor(ConsoleColor::WHITE)
->setBackground(ConsoleBackground::RED)
->setFormat([ConsoleFormat::BOLD, ConsoleFormat::UNDERLINE]);
// or
$formatter->style('alert')
->parseStyle('clr=white bg=red fmt=bold,underline');
As soon as you've register a style, it will be applied to matching tags. If a style is unknown, the tag will be ignored. Example below will output properly formatted text.
echo $formatter->format('<alert>text</alert>');
You can apply styling inline, without having to register a new style. To do that you must use the <style></style>
tag.
echo $formatter->format('<style clr=red bg=white>red text on white background</style>');
You can also use inline styling on predefined styles.
$formatter->format('<alert clr=yellow>alert style with yellow text</alert>');
Whenever you have nested styles, one style might inherit from the parent. This is disabled by default to prevent unwanted styles changes. You can enable it for each style separately.
$formatter->style('name')
->setAllowInheritance(true);
If you're working with a terminal that does not support ANSI, you can disable formatting. All known style tags will be removed from the string.
$formatter->setEnableAnsi(false);
// will return: alert <unknown>tag</unknown>
$formatter->format('<style clr=red><alert>alert <unknown>tag</unknown></alert></style>');
You can run the examples.php
file to see if it works on your system.