regex

Quick and dirty way to strip ANSI terminal output in PHP

From time to time, I write up little PHP scripts to run a command via exec() and dump the output to the screen. Most of the time these are quick throwaway scripts, but sometimes I need them to persist a little longer, or share the output with others, so I make them look a little nicer.

One annoying thing that happens if you interact with CLI tools that generate colorized output is that PHP doesn't translate the terminal (ANSI) color codes into HTML colors, so you end up looking at output like:

Kubernetes master is running at https://10.96.0.1:443

Sensio Labs maintains an excellent ansi-to-html PHP library, and if you're building anything that should be persistent or robust, you should use it. But I wanted a one-line solution for one simple script I was working on, so I spent a couple minutes building out the following regex:

The best way to get the full PHP version string

Recently, to automate building, tagging, and pushing my geerlingguy/php-apache Docker Hub image (see this issue), I needed to find a way to reliably determine the PHP major.minor.release version string. You'd think this would be simple.

Well, using Docker, I would run the image and then try:

# php --version
PHP 7.3.0-1+0~20181206202713.23+stretch~1.gbp076afd (cli) (built: Dec  6 2018 20:27:14) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.0-dev, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.0-1+0~20181206202713.23+stretch~1.gbp076afd, Copyright (c) 1999-2018, by Zend Technologies

That's great; it outputs the version right at the start. But there are a few problems here: