Clear PHP CLI output

Linux下清除Terminal输出信息的方法

网上看到一种特别的想法,透过Ansi编码控制输出信息,记录一下以备不时之需。


function replaceOut($str$finish = false) {
	// chr(27) = Esc
    echo chr(27) . "[0G"; // Set cursor to first column
    echo $str;
    if(!$finish) {
		$numNewLines = substr_count($str, "\n");
    	echo chr(27) . "[" . $numNewLines ."A";  // 游标向上退回 N 行(N 个换行符)
	}
}

while (true) {
    replaceOut("First Line\nTime: " . date('Y-m-d H:i:s') . "\nThird Line");
    sleep(1);
}

/*
Output: (第二行会像时钟般跳动)
 	First Line
 	2020-04-14 15:52:22
 	Third Line
 */
?>

另外如果只想在Terminal上显示,不想被导向档案的话...

	$is_tty = function_exists('posix_isatty') && posix_isatty(STDOUT);
	// true => Terminal, false => Redirect to file.
?>

Ansi Escape commands: http://www.inwap.com/pdp10/ansicode.txt

Ref: https://stackoverflow.com/a/11424357

你可能感兴趣的:(PHP,php)