LINKeRxUA
LINKeRxUA

Reputation: 559

Is it possible to get width of terminal or to print line with fill of 100% width?

PHP. fputs(STDOUT, 'some short text')! Is there any way to get char length for terminal that launch php script?

How to print text with fputs(STDOUT, "Some Error\n"); with full line background of red color?

Upvotes: 4

Views: 1737

Answers (2)

Tomas Votruba
Tomas Votruba

Reputation: 24280

You can use Symfony\Console for this, since it has Terminal class that does exactly what you need:

Install with composer

composer require symfony/console

Create script index.php

<?php

require __DIR__ . '/vendor/autoload.php';

$terminal = new Symfony\Component\Console\Terminal;

$terminalWidth = $terminal->getWidth();
var_dump($terminalWidth);

Test it

$ php index.php
int(80)

Upvotes: 3

Clinton Lam
Clinton Lam

Reputation: 727

This will output a line with "=" characters filling the whole line of the terminal. Will work on linux-based system.

// 'tput cols' is a shell command which returns
//   the number of chars to fill up the whole
//   line of the current terminal.
$colCount = shell_exec('tput cols');

// Create the string filling the whole line
$string = str_repeat("=", intval($colCount));

// This is the way to print out text with coloured background
// 48, 5, 160 representing 256-colour of red, green and blue.
fputs(STDOUT, "\e[48;5;160m".$string."\e[0m");

Which can be condensed to one line

fputs(STDOUT, "\e[48;5;160m".str_repeat("=", intval(shell_exec('tput cols')))."\e[0m");

Here's a script to ANSI color code in XTerm/ANSI-compatible terminals with a 256-color palette support if you want to know more about displaying colours on terminal.

Upvotes: 5

Related Questions