ANSI Control Functions and ANSI Control Sequences (Colors, Erasing, etc.) for PHP CLI Apps

As a side project for Monolog Colored Line Formatter (which int itself also is a side project for Mixed Content Scan) I just published is ANSI PHP.

bramus/ansi-php is a set of classes to working with ANSI Control Functions and ANSI Control Sequences (ANSI Escape Sequences) on text based terminals.

  • ANSI Control Functions control an action such as line spacing, paging, or data flow.
  • ANSI Control Sequences allow one to clear the screen, move the cursor, set text colors, etc.

When it comes to ANSI Escape Sequences bramus/ansi-php supports SGR (Select Graphic Rendition) and ED (Erase Display)

  • SGR affords one to manipulate text styling (bold, underline, blink, colors, etc.).
  • ED allows one to erase the display.

Other Control Sequences – such as moving the cursor – are not (yet) supported.

It differs from other “PHP ANSI Color” attempts by not being limited to SGR only – it can easily be extended to support other ANSI Escape Sequences – and by supporting all SGR parameters.

The library ships with an Ansi helper class to easily use it.

use \Bramus\Ansi\Ansi;
use \Bramus\Ansi\ControlSequences\EscapeSequences\Enums\SGR;

// Create Ansi Instance
$a = new Ansi();

// Output some styled text on screen, along with a Line Feed and a Bell
echo $a->color(array(SGR::COLOR_FG_RED, SGR::COLOR_BG_WHITE))
       ->blink()
       ->text('My text will be white on a red background and I will be blinking.')
       ->nostyle()
       ->lf()
       ->text('I will be normally styled. Oh, a bell is coming up ...')
       ->bell()
       ->get();

Installation is possible via Composer:

composer require bramus/ansi-php ~2.0

ANSI PHP — ANSI Control Functions and ANSI Control Sequences (Colors, Erasing, etc.) for PHP CLI Apps →

Did this help you out? Like what you see?
Consider donating.

I don’t run ads on my blog nor do I do this for profit. A donation however would always put a smile on my face though. Thanks!

☕️ Buy me a Coffee ($3)

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.