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

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:

Getting Ping statistics with PHP

[Note: Since writing this post, I've created the Ping class for PHP, which incorporates three different ping/latency/uptime methods for PHP, and is a lot more robust than the script I have posted below.]

I recently needed to display some ping/server statistics on a website using PHP. The simplest way to do something like this is to use the built-in linux utility ping, and then parse the results. Instead of doing complex regex with the entirety of ping's output, though, I also used a couple other built-in linux utilities to get just what I needed.

Here's how I got just the response time of a given IP address:

= '123.456.789.0'; // IP address you'd like to ping.
exec("ping -c 1 " . $ip_address . " | head -n 2 | tail -n 1 | awk '{print $7}'", $ping_time);
$ping_time[0]; // First item in array, since exec returns an array.

The above script will ping the given IP address, and simply pull out the response time in milliseconds. You can further parse the response time to just be the numeric value by running it through substr($ping_time[0], 5).