1
0

terminal-color-output.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * dolphin. Collection of useful PHP skeletons.
  4. * Copyright (C) 2011 Johannes 'Banana' Keßler
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
  8. *
  9. * You should have received a copy of the
  10. * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11. * along with this program. If not, see http://www.sun.com/cddl/cddl.html
  12. */
  13. /**
  14. * return given $string with ASCII commands to be colored in terminal
  15. * works with apple and unix, but not with windows
  16. *
  17. * usage: echo cO('Some Text','red');
  18. * new line is added automatically
  19. *
  20. * @param string $string The text to be colored
  21. * @param string $col The text color
  22. * @param string $bcol The background color. Default is not set
  23. * @param string $ret The formatted ( or not ) text
  24. */
  25. function cO($string,$col,$bcol=false) {
  26. $ret = false;
  27. if(empty($string)) return $string;
  28. $_foregroundColors = array(
  29. 'black' => '0;30',
  30. 'dark_gray' => '1;30',
  31. 'blue' => '0;34',
  32. 'light_blue' => '1;34',
  33. 'green' => '0;32',
  34. 'light_green' => '1;32',
  35. 'cyan' => '0;36',
  36. 'light_cyan' => '1;36',
  37. 'red' => '0;31',
  38. 'light_red' => '1;31',
  39. 'purple' => '0;35',
  40. 'light_purple' => '1;35',
  41. 'brown' => '0;33',
  42. 'yellow' => '1;33',
  43. 'light_gray' => '0;37',
  44. 'white' => '1;37',
  45. 'black_u' => '4;30', // underlined
  46. 'red_u' => '4;31',
  47. 'green_u' => '4;32',
  48. 'yellow_u' => '4;33',
  49. 'blue_u' => '4;34',
  50. 'purple_u' => '4;35',
  51. 'cyan_u' => '4;36',
  52. 'white_u' => '4;37'
  53. );
  54. $_backgroundColors = array(
  55. 'black' => '40',
  56. 'red' => '41',
  57. 'green' => '42',
  58. 'yellow' => '43',
  59. 'blue' => '44',
  60. 'magenta' => '45',
  61. 'cyan' => '46',
  62. 'light_gray' => '47'
  63. );
  64. if (isset($_foregroundColors[$col])) {
  65. $ret .= "\033[" . $_foregroundColors[$col] . "m";
  66. }
  67. if (isset($_backgroundColors[$bcol])) {
  68. $ret .= "\033[" . $_backgroundColors[$bcol] . "m";
  69. }
  70. if(!empty($ret)) {
  71. $ret .= $string."\033[0m";
  72. }
  73. else {
  74. $ret = $string;
  75. }
  76. return $ret."\n";
  77. }
  78. ?>