Как изменить цвет текста php

What's the easiest way to change a text's color based on a variable? For example: If $var is between 1-5, green. Between 6-10, Orange. Greater than 11, Red.

What’s the easiest way to change a text’s color based on a variable?

For example: If $var is between 1-5, green. Between 6-10, Orange. Greater than 11, Red.

PeeHaa's user avatar

PeeHaa

70.7k58 gold badges187 silver badges260 bronze badges

asked May 10, 2010 at 15:59

Kevin Brown's user avatar

Kevin BrownKevin Brown

12.5k34 gold badges94 silver badges155 bronze badges

6

function getProperColor($number)
{
    if ($var > 0 && $var <= 5)
        return '#00FF00';
    else if ($var >= 6 && $var <= 10)
        return = '#FF8000';
    else if ($var >= 11)
        return = '#FF0000';
}

And use it like this

<div style="background-color: <?=getProperColor($result['number'])?>;"><?=$result["title"]?></div>

answered May 10, 2010 at 16:05

sshow's user avatar

7

$color = "#000000";

if (($v >= 1) && ($v <= 5))
   $color = "#00FF00";
else if (($v >= 6) && ($v <= 10))
   $color = "#FF9900";
else if ($v >= 11)
   $color = "#FF0000";

echo "<span style="color: $color">Text</span>";

answered May 10, 2010 at 16:03

LukeN's user avatar

LukeNLukeN

5,5601 gold badge24 silver badges32 bronze badges

6

Are color values indexed by constants? I would prepare hash map

$colorMap[0] = '#00FF00'; //green
$colorMap[1] = '#0000FF'; //blue
$colorMap[2] = '#FF0000'; //red
$colorMap[3] = '#330000'; //dark red

and so on. Then use CSS

<span style="color: <?php echo $colorMap[$var]; ?>;">desired color</span>

answered May 10, 2010 at 16:08

mip's user avatar

mipmip

8,1876 gold badges50 silver badges71 bronze badges

0

A simple solution might be to do something like this…

if ($var < 6)
    $style="0F0";
else if ($var < 11)
    $style="F50";
else
   $style = "F00";

?><div style="color:#<?php echo $style; ?>">blar</div>

answered May 10, 2010 at 16:04

Rik Heywood's user avatar

Rik HeywoodRik Heywood

13.7k9 gold badges60 silver badges81 bronze badges

You need to actually use elseif statements if your going to use a set of if statements,

 if ($var < 6) $color = '#00FF00';
elseif ($var < 10) $color = '#FF8000';
elseif ($var > 10) $color = '#FF0000';

answered May 10, 2010 at 16:05

fafnirbcrow's user avatar

fafnirbcrowfafnirbcrow

2703 silver badges8 bronze badges

1

I’ll use CSS colors and also highlight the fact that the number 11 does not map to any color according to your rules making most of the answers invalid :)

<?php

$color=getColor(11);

function getColor($n){

    // Is number between 1 and 5?
    if($n>=1 && $n<=5) return "green";

    // Is number between 6 and 10?
    if($n>=6 && $n<=10) return "orange";

    // Is number greater than 11
    if($n>11) return "red";

    // Return default (black) for all other numbers
    return "black";

}

?>

<span style='color:<?=$color?>'>Text</span>

answered May 10, 2010 at 16:23

zaf's user avatar

zafzaf

22.6k12 gold badges64 silver badges95 bronze badges

Something like this trio of if statements:

if ($var < 10) $color = '#FF8000';
if ($var < 6) $color = '#00FF00';
if ($var >= 10) $color = '#FF0000';

echo "<span style="color: $color;">This text is colored.</span>";

answered May 10, 2010 at 16:02

JYelton's user avatar

JYeltonJYelton

35.1k27 gold badges128 silver badges190 bronze badges

3

Ternary operator for your simple example.

  $color = ($var < 6) ? '#FF8000' :  (($var < 10) ? '#00FF00' : '#FF0000');

answered May 10, 2010 at 17:24

alexganose's user avatar

alexganosealexganose

2274 silver badges12 bronze badges

I would use CSS classes instead of inline styling the color… Let CSS work…

<?php
$var = 5;
$class = (($var < 6) ? 'greenclass' : (($var < 11) ? 'orangeclass' : 'redclass' ))
?>
<span class="<?php echo $class?>">text</div>

If none of these answers are the one you expect, what exactly are you trying to accomplish? Can you give more info?

answered May 10, 2010 at 16:28

acm's user avatar

acmacm

6,5263 gold badges37 silver badges44 bronze badges

answered Dec 17, 2010 at 16:28

Kevin Brown's user avatar

Kevin BrownKevin Brown

12.5k34 gold badges94 silver badges155 bronze badges

Assuming one works with ranges than this is quite flexible:

function getProperColor($range, $value)
{
    foreach($range as $key => $color)
    {
        if ($value <= $key)
            return $color;
    }
    return $color;
}

$colorRange = array(
    5 => 'green',
    10 => 'orange',
    11 => 'red'
);

for($i=-1;$i<16;$i+=2)
{
    echo "$i:" . getProperColor($colorRange, $i) . "n";
}

This will output:

-1:green
1:green
3:green
5:green
7:orange
9:orange
11:red
13:red
15:red

answered Jul 12, 2013 at 1:03

Finzzownt's user avatar

FinzzowntFinzzownt

3703 silver badges6 bronze badges

1

<?php
$var='2';
?>
 <html>
  <body>
   <p>Hello Welcome.I am
     <?php 
      if($var>0 && $var<=5)
        echo '<p style=color:Green;>';
      else if($var>=6 && $var<= 10)
        echo '<p style=color:orange;>';
      else
         echo '<p style=color:red;>';
?>
        I am a Developer.
     </p>
     </body>

answered Jun 13, 2014 at 12:55

Alekhya's user avatar

why not a switch case ? it would be cleaner this way

   $color = "";
   switch(true){
      case ($var > 0 && $var <= 5):
            $color = '#00FF00';
      break;
      case ($var >= 6 && $var <= 10):
            $color = '#00FF00';
      break;
      case ($var >= 11):
            $color = '#00FF00';
      break;
      default:
            $color = '#000000';

answered Apr 12, 2018 at 7:56

JeremyGi's user avatar

2

$color="green";
$text="foo";
echo wrapColor($color, $text);

function wrapColor($color, $text){
return "<span style=color:$color>$text</span>";
}

answered May 10, 2010 at 16:05

Chad's user avatar

ChadChad

3822 silver badges7 bronze badges

1

(PHP 4, PHP 5, PHP 7, PHP 8)

highlight_stringSyntax highlighting of a string

Description

highlight_string(string $string, bool $return = false): string|bool

Outputs or returns html markup for a syntax highlighted version of the given PHP code
using the colors defined in the built-in syntax highlighter for PHP.

Parameters

string

The PHP code to be highlighted. This should include the opening tag.

return

Set this parameter to true to make this function return the
highlighted code.

Return Values

If return is set to true, returns the highlighted
code as a string instead of printing it out. Otherwise, it will return
true on success, false on failure.

Examples

Example #1 highlight_string() example


<?php
highlight_string
('<?php phpinfo(); ?>');
?>

The above example will output:

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

Notes

Note:

When the return parameter
is used, this function uses internal output buffering so it cannot be used inside an
ob_start() callback function.

The HTML markup generated is subject to change.

stanislav dot eckert at vizson dot de

7 years ago


You can change the colors of the highlighting, like this:

<?php
ini_set
("highlight.comment", "#008000");
ini_set("highlight.default", "#000000");
ini_set("highlight.html", "#808080");
ini_set("highlight.keyword", "#0000BB; font-weight: bold");
ini_set("highlight.string", "#DD0000");
?>

Like you see in the example above, you can even add additional styles like bold text, since the values are set directly to the DOM attribute "style".

Also, this function highlights only text, if it begins with the prefix "<?php". But this function can highlight other similar formats too (not perfectly, but better than nothing), like HTML, XML, C++, JavaScript, etc. I use following function to highlight different file types and it works quite good:

<?php
function highlightText($text)
{
   
$text = trim($text);
   
$text = highlight_string("<?php " . $text, true);  // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
   
$text = trim($text);
   
$text = preg_replace("|^\<code\>\<span style\="color\: #[a-fA-F0-9]{0,6}"\>|", "", $text, 1);  // remove prefix
   
$text = preg_replace("|\</code\>$|", "", $text, 1);  // remove suffix 1
   
$text = trim($text);  // remove line breaks
   
$text = preg_replace("|\</span\>$|", "", $text, 1);  // remove suffix 2
   
$text = trim($text);  // remove line breaks
   
$text = preg_replace("|^(\<span style\="color\: #[a-fA-F0-9]{0,6}"\>)(&lt;\?php&nbsp;)(.*?)(\</span\>)|", "$1$3$4", $text);  // remove custom added "<?php "return $text;
}
?>

Note, that it will remove the <code> tag too, so you get the formatted text directly, which gives you more freedom to work with the result.

I personally suggest to combine both things to have a nice highlighting function for different file types with different highlight coloring sets:

<?php
function highlightText($text, $fileExt="")
{
    if (
$fileExt == "php")
    {
       
ini_set("highlight.comment", "#008000");
       
ini_set("highlight.default", "#000000");
       
ini_set("highlight.html", "#808080");
       
ini_set("highlight.keyword", "#0000BB; font-weight: bold");
       
ini_set("highlight.string", "#DD0000");
    }
    else if (
$fileExt == "html")
    {
       
ini_set("highlight.comment", "green");
       
ini_set("highlight.default", "#CC0000");
       
ini_set("highlight.html", "#000000");
       
ini_set("highlight.keyword", "black; font-weight: bold");
       
ini_set("highlight.string", "#0000FF");
    }
   
// ...$text = trim($text);
   
$text = highlight_string("<?php " . $text, true);  // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
   
$text = trim($text);
   
$text = preg_replace("|^\<code\>\<span style\="color\: #[a-fA-F0-9]{0,6}"\>|", "", $text, 1);  // remove prefix
   
$text = preg_replace("|\</code\>$|", "", $text, 1);  // remove suffix 1
   
$text = trim($text);  // remove line breaks
   
$text = preg_replace("|\</span\>$|", "", $text, 1);  // remove suffix 2
   
$text = trim($text);  // remove line breaks
   
$text = preg_replace("|^(\<span style\="color\: #[a-fA-F0-9]{0,6}"\>)(&lt;\?php&nbsp;)(.*?)(\</span\>)|", "$1$3$4", $text);  // remove custom added "<?php "return $text;
}
?>


www.phella.net

15 years ago


When you quote highlighted PHP code in your website you need to escape quotes. If you quote a lot it may be annoyning. Here is tiny snippet how to make quoting tidy and clean. Write your code like this:

<?code()?>
  $string = 'Here I put my code';
<?code()?>

And somewhere else define the function:

<?
  function code()
  {
    static $on=false;
    if (!$on) ob_start();
    else
    {
      $buffer= "<?n".ob_get_contents()."?>";
      ob_end_clean();
      highlight_string($buffer);
    }
    $on=!$on;
  }
?>


pyetrosafe at gmail dot com

4 years ago


I read the note from "stanislav dot eckert at vizson dot de" and I really enjoyed the function he created.
For my use I made some adaptations leaving the function more practical and allowing the passage and multiple parameters at a time, I also modified the style of the <code> element with a black background and margins.

<?php// Combined of the highlight_string and var_export
function hl_export()
{
    try {
       
ini_set("highlight.comment", "#008000");
       
ini_set("highlight.default", "#FFFFFF");
       
ini_set("highlight.html", "#808080");
       
ini_set("highlight.keyword", "#0099FF; font-weight: bold");
       
ini_set("highlight.string", "#99FF99");$vars = func_get_args();

        foreach (

$vars as $var ) {
           
$output = var_export($var, true);
           
$output = trim($output);
           
$output = highlight_string("<?php " . $output, true);  // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
           
$output = preg_replace("|\<code\>|", "<code style='background-color: #000000; padding: 10px; margin: 10px; display: block; font: 12px Consolas;'>", $output, 1);  // edit prefix
           
$output = preg_replace("|(\<span style\="color\: #[a-fA-F0-9]{0,6}"\>)(&lt;\?php&nbsp;)(.*?)(\</span\>)|", "$1$3$4", $output);  // remove custom added "<?php "
           
echo $output;
        }
    } catch (
Exception $e) {
        echo
$e->getMessage();
    }
}
// Debug multiple vars at once.
$var1 = 'Example String';
$var2 = 1987;
$var3 = null;
$var4 = true;
$var5 = array('Array', '05', 05, false, null);hl_export( $var1, $var2, $var3, $var4, $var5 );
?>


vouksh at vouksh dot info

17 years ago


Fully working, XHTML 1.1 ready xhtml_highlight function. I included the stripslashes, because of some problems I had with out it. It should be safe to leave it in there, but if you experience problems, feel free to take it out.

<?
function xhtml_highlight($str) {
    $hlt = highlight_string(stripslashes($str), true);
    $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
    $ret = preg_replace('#color="(.*?)"#', 'style="color: \1"', $fon);
    echo $ret;
    return true;
}
?>


fsx dot nr01 at gmail dot com

14 years ago


Here is an improved version of the code highlighter w/ linenumbers from 'vanessaschissato at gmail dot com' - http://nl.php.net/manual/en/function.highlight-string.php#70456

<?phpfunction printCode($source_code)
    {

        if (

is_array($source_code))
            return
false;$source_code = explode("n", str_replace(array("rn", "r"), "n", $source_code));
       
$line_count = 1;

        foreach (

$source_code as $code_line)
        {
           
$formatted_code .= '<tr><td>'.$line_count.'</td>';
           
$line_count++;

                       if (

ereg('<?(php)?[^[:graph:]]', $code_line))
               
$formatted_code .= '<td>'. str_replace(array('<code>', '</code>'), '', highlight_string($code_line, true)).'</td></tr>';
            else
               
$formatted_code .= '<td>'.ereg_replace('(&lt;?php&nbsp;)+', '', str_replace(array('<code>', '</code>'), '', highlight_string('<?php '.$code_line, true))).'</td></tr>';
        }

        return

'<table style="font: 1em Consolas, 'andale mono', 'monotype.com', 'lucida console', monospace;">'.$formatted_code.'</table>';
    }
?>


Pyerre

15 years ago


This fonction replaces every space with the html code &nbsp; (non-breaking space)
this is not very good because text will not go to the line and causes a big width
for example in a bordered div, text will go across the border

my solution :
echo str_replace("&nbsp;", " ",highlight_string("Arise, you children of the fatherland",true));
echo str_replace("&nbsp;", " ",highlight_file("test.php",true));


stalker at ruun dot de

17 years ago


to vouksh: I expanded your functions a bit:

<?php
function xhtmlHighlightString($str,$return=false) {
  
$hlt = highlight_string(stripslashes($str), true);
  
$fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
  
$ret = preg_replace('#color="(.*?)"#', 'style="color: \1"', $fon);
   if(
$return)
     return
$ret;
   echo
$ret;
   return
true;
}
function
xhtmlHighlightFile($path,$return=false) {
  
$hlt = highlight_file($path, true);
  
$fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
  
$ret = preg_replace('#color="(.*?)"#', 'style="color: \1"', $fon);
   if(
$return)
     return
$ret;
   echo
$ret;
   return
true;
}
?>


admin [at] develogix [dot] com

17 years ago


I've been working on a good replacement for the highlight_string() function; and here is what I've come up with so far:

<?
function get_sourcecode_string($str, $return = false, $counting = true, $first_line_num = '1', $font_color = '#666'){
    $str = highlight_string($str, TRUE);
    $replace = array(
        '<font' => '<span',
        'color="' => 'style="color: ',
        '</font>' => '</span>',
        '<code>' => '',
        '</code>' => '',
        '<span style="color: #FF8000">' =>
            '<span style="color: '.$font_color.'">'
        );
    foreach ($replace as $html => $xhtml){
        $str = str_replace($html, $xhtml, $str);
    }
    // delete the first <span style="color:#000000;"> and the corresponding </span>
    $str = substr($str, 30, -9);

                    $arr_html      = explode('<br />', $str);
    $total_lines   = count($arr_html);   
    $out           = '';
    $line_counter  = 0;
    $last_line_num = $first_line_num + $total_lines;

        foreach ($arr_html as $line){
        $line = str_replace(chr(13), '', $line);
        $current_line = $first_line_num + $line_counter;
        if ($counting){
            $out .= '<span style="color:'.$font_color.'">'
                  . str_repeat('&nbsp;', strlen($last_line_num) - strlen($current_line))
                  . $current_line
                  . ': </span>';
        }
        $out .= $line
              . '<br />'."n";
        $line_counter++;
    }
    $out = '<code>'."n".$out.'</code>."n"';

    if ($return){return $out;}
    else {echo $out;}
}
?>

This function outputs valid XHTML 1.1 code by replacing font tags with span tags. You can also specify whether you want it to return or echo, output a line-count, the color of the line-count, and the starting line-count number.

Usage:
<?
// $str = string with php
// $return = true (return) / false (echo)
//    default of false
// $counting = true (count) / false (don't count)
//    default of true
// $start = starting count number
//    default of '1'
// $color = count color with preceding #
//    defalut of '#666'
get_sourcecode_string($str, $return,   $counting, $start, $color);
?>


manithu at fahr-zur-hoelle dot org

18 years ago


This function will return highlighted, xhtml 1.1 valid code (replaces <font> with <span> elements and color with style attributes):

<?phpfunction xhtml_highlight($str) {
   
$str = highlight_string($str, true);
   
//replace <code><font color=""></font></code>
   
$str = preg_replace('#<font color="([^']*)">([^']*)</font>#', '<span style="color: \1">\2</span>', $str);
   
//replace other <font> elements
   
return preg_replace('#<font color="([^']*)">([^']*)</font>#U', '<span style="color: \1">\2</span>', $str);
}
?>


stanislav dot eckert at vizson dot de

7 years ago


The documentation says for the first parameter "The PHP code to be highlighted. This should include the opening tag. ". But it seems that the code should not only but *must* start with PHP's opening tag or otherwise the function will still modify but will not highlight the code.

wm at tellinya dot com

15 years ago


I wanted to build a better function and exclude operators {}=- from keywords span class. I also wanted to link functions used in my PHP code directly to the PHP site.
A lot more changes and tweaks have been made and the output is much better!

Find the function here :
http://www.tellinya.com/art2/262/highligh-php-syntax/
and ditch the old PHP one permanently.
Tested and built on PHP 5.2.0.

Looking forward to any input.


Dobromir Velev

14 years ago


Here is an improved version of Dimitry's xml_highlight function.
I fixed a bug which replaced the first character of the tags name,
and added a line to replace the tabs and spaces with
non-breaking space symbols to keep the identation.

<?
function xml_highlight($s){
  $s = preg_replace("|<([^/?])(.*)s(.*)>|isU", "[1]<[2]\1\2[/2] [5]\3[/5]>[/1]", $s);
  $s = preg_replace("|</(.*)>|isU", "[1]</[2]\1[/2]>[/1]", $s);
  $s = preg_replace("|<?(.*)?>|isU","[3]<?\1?>[/3]", $s);
  $s = preg_replace("|="(.*)"|isU", "[6]=[/6][4]"\1"[/4]",$s);
  $s = htmlspecialchars($s);
  $s = str_replace("t","&nbsp;&nbsp;",$s);
  $s = str_replace(" ","&nbsp;",$s);
  $replace = array(1=>'0000FF', 2=>'0000FF', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
  foreach($replace as $k=>$v) {
    $s = preg_replace("|[".$k."](.*)[/".$k."]|isU", "<font color="#".$v."">\1</font>", $s);
  }

  return nl2br($s);
}
?>


zer0

17 years ago


Concerning my code below:

I'm sorry, I completely forgot about str_ireplace being for PHP 5 for some reason. Also, there was another error I missed (too many late nights ;)). Here's the corrected code:

<?php
   
function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
   
{
        (string)
$highlight = "";
        if (
version_compare(PHP_VERSION, "4.2.0", "<") === 1 )
        {
           
ob_start(); // start output buffering to capture contents of highlight
           
highlight_string($code);
           
$highlight = ob_get_contents(); // capture output
           
ob_end_clean(); // clear buffer cleanly
       
}
        else
        {
           
$highlight=highlight_string($code, true);
        }
# Using preg_replace will allow PHP 4 in on the fun
       
if ( $inline === true )
           
$highlight=preg_replace("/<code>/i","<code class="inline">",$highlight);
        else
           
$highlight=preg_replace("/<code>/i","<code class="block">",$highlight);           

                if (

$return === true )
        {
            return
$highlight;
        }
        else
        {
            echo
$highlight;
        }
    }
?>


bpgordon at gmail dot com

17 years ago


On dleavitt AT ucsc DOT edu's comment:

You might want to use md5($html_string) instead of "piggusmaloy" as a generally good programming practice. Just in case "piggusmaloy" is actually in $html_string.


Dmitry S

14 years ago


Alternative XML syntax highlighting.

<?php
function xml_highlight($s)
{       
   
$s = htmlspecialchars($s);
   
$s = preg_replace("#&lt;([/]*?)(.*)([s]*?)&gt;#sU",
       
"<font color="#0000FF">&lt;\1\2\3&gt;</font>",$s);
   
$s = preg_replace("#&lt;([?])(.*)([?])&gt;#sU",
       
"<font color="#800000">&lt;\1\2\3&gt;</font>",$s);
   
$s = preg_replace("#&lt;([^s?/=])(.*)([[s/]|&gt;)#iU",
       
"&lt;<font color="#808000">\1\2</font>\3",$s);
   
$s = preg_replace("#&lt;([/])([^s]*?)([s]]*?)&gt;#iU",
       
"&lt;\1<font color="#808000">\2</font>\3&gt;",$s);
   
$s = preg_replace("#([^s]*?)=(&quot;|')(.*)(&quot;|')#isU",
       
"<font color="#800080">\1</font>=<font color="#FF00FF">\2\3\4</font>",$s);
   
$s = preg_replace("#&lt;(.*)([)(.*)(])&gt;#isU",
       
"&lt;\1<font color="#800080">\2\3\4</font>&gt;",$s);
    return
nl2br($s);
}
?>


gaggge at gmail dot com

18 years ago


This is a little function for highlighting bbcode-stylish PHP code from a mysql database.
(Like this: [php]<?php echo "test"; ?>[/php])

<?php
function bbcode($s)
{
   
$s = str_replace("]n", "]", $s);
   
$match = array('#[php](.*?)[/php]#se');
   
$replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
    return
preg_replace($match, $replace, $s);
}
?>


admin at bwongar dot com

18 years ago


I didn't get the expected results from the other XHTML_highlight function, so I developed my own and it is much more efficient. The older one uses a preg_replace to replace the contents of the tag to within a span tag. The only preg_replace in my function pulls the color attribute, and puts it within a str_replace'd span tag.

<?php
function xhtml_highlight($str) {
   
$str = highlight_string($str, true);
   
$str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
    return
preg_replace('#color="(.*?)"#', 'style="color: \1"', $str);
}
?>


Mean^_^

13 years ago


[EDIT BY danbrown AT php DOT net: The following note contains a user-supplied version of a syntax highlighter.]

<style type="text/css">

.linenum{

    text-align:right;

    background:#FDECE1;

    border:1px solid #cc6666;

    padding:0px 1px 0px 1px;

    font-family:Courier New, Courier;

    float:left;

    width:17px;

    margin:3px 0px 30px 0px;

    }

code    {/* safari/konq hack */

    font-family:Courier New, Courier;

}

.linetext{

    width:700px;

    text-align:left;

    background:white;

    border:1px solid #cc6666;

    border-left:0px;

    padding:0px 1px 0px 8px;

    font-family:Courier New, Courier;

    float:left;

    margin:3px 0px 30px 0px;

    }

br.clear    {

    clear:both;

}

</style>

<?php
function printCode($code, $lines_number = 0)    {

              
         if (!

is_array($code)) $codeE = explode("n", $code);

       
$count_lines = count($codeE);
$r1 = "Code:<br />";

         if (

$lines_number){           

               
$r1 .= "<div class="linenum">";

                foreach(
$codeE as $line =>$c) {    

                    if(
$count_lines=='1')

                       
$r1 .= "1<br>";

                    else

                       
$r1 .= ($line == ($count_lines - 1)) ? "" :  ($line+1)."<br />";

                 }

                
$r1 .= "</div>";

         }
$r2 = "<div class="linetext">";

        
$r2 .= highlight_string($code,1);

        
$r2 .= "</div>";
$r .= $r1.$r2;

        echo

"<div class="code">".$r."</div>n";

    }
printCode('<?php echo "PHP Code" ?>    ',1);

?>



by mean

Share idea.

good luck ^_^


Daniel

14 years ago


Well, Just a little something I wrote which highlights an HTML code...It'll be going through many changes in the next few days.... until then =) enjoy

<?php
/*************************************
CODE PANE 1.0 - SILVERWINGS - D. Suissa
*************************************/
class HTMLcolorizer{
    private
$pointer = 0; //Cursor position.
   
private $content = null; //content of document.
   
private $colorized = null;
    function
__construct($content){
       
$this->content = $content;
    }
    function
colorComment($position){
       
$buffer = "&lt;<span class='HTMLComment'>";
        for(
$position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
           
$buffer.= $this->content[$position];
        }
       
$buffer .= "</span>&gt;";
       
$this->colorized .= $buffer;
        return
$position;
    }
    function
colorTag($position){
       
$buffer = "&lt;<span class='tagName'>";
       
$coloredTagName = false;
       
//As long as we're in the tag scope
       
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
            if(
$this->content[$position] == " " && !$coloredTagName){
               
$coloredTagName = true;
               
$buffer.="</span>";
            }else if(
$this->content[$position] != " " && $coloredTagName){
               
//Expect attribute
               
$attribute = "";
               
//While we're in the tag
               
for(;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
                    if(
$this->content[$position] != "="){
                       
$attribute .= $this->content[$position];
                    }else{
                       
$value="";
                       
$buffer .= "<span class='tagAttribute'>".$attribute."</span>=";
                       
$attribute = ""; //initialize it
                       
$inQuote = false;
                       
$QuoteType = null;
                        for(
$position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != " "  ;$position++){
                            if(
$this->content[$position] == '"' || $this->content[$position] == "'"){
                               
$inQuote = true;
                               
$QuoteType = $this->content[$position];
                               
$value.=$QuoteType;
                               
//Read Until next quotation mark.
                               
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != $QuoteType  ;$position++){
                                   
$value .= $this->content[$position];
                                }   
                               
$value.=$QuoteType;
                            }else{
//No Quotation marks.
                               
$value .= $this->content[$position];
                            }                           
                        }
                       
$buffer .= "<span class='tagValue'>".$value."</span>";
                        break;           
                    }

                                    }
                if(

$attribute != ""){$buffer.="<span class='tagAttribute'>".$attribute."</span>";}
            }
            if(
$this->content[$position] == ">" ){break;}else{$buffer.= $this->content[$position];}

                    }

//In case there were no attributes.
       
if($this->content[$position] == ">" && !$coloredTagName){
           
$buffer.="</span>&gt;";
           
$position++;
        }
       
$this->colorized .= $buffer;
        return --
$position;
    }
    function
colorize(){
       
$this->colorized="";
       
$inTag = false;
        for(
$pointer = 0;$pointer<strlen($this->content);$pointer++){
           
$thisChar = $this->content[$pointer];
           
$nextChar = $this->content[$pointer+1];
            if(
$thisChar == "<"){
                if(
$nextChar == "!"){
                   
$pointer = $this->colorComment($pointer);
                }else if(
$nextChar == "?"){
                   
//colorPHP();
               
}else{
                   
$pointer = $this->colorTag($pointer);
                }
            }else{
               
$this->colorized .= $this->content[$pointer];
            }
        }
        return
$this->colorized;
    }
}
$curDocName = $_REQUEST['doc'];
$docHandle = fopen($curDocName,"r");
$docStrContent = fread($docHandle,filesize($curDocName));
fclose($docHandle);
$HTMLinspector = new HTMLcolorizer($docStrContent);
$document = $HTMLinspector->colorize();
?>

<html>
    <head>
        <style type="text/css">
        /**********************
         * MOZILLA FIREFOX STYLE
        **********************/
        /*pre{font-family:Tahoma;font-size:px;}*/
        .tagName{color:purple;}
        .tagAttribute{color:red;}
        .tagValue{color:blue;}
        .HTMLComment{font-style:italic;color:green;}
        </style>
    </head>
    <body>
    <?php
       
echo "<pre>".$document."</pre>";
   
?>
    </body>
</html>


Sam Wilson

17 years ago


manithu at fahr-zur-hoelle dot org forgot only one thing:  to fix the break tags.  The addidtion of the following should do it.

<?php
$str
= str_replace("<br>", "<br />", $str);
?>


trixsey at animania dot nu

17 years ago


A neat function I made. Syntax coloring, row numbers, varying background colors per row in the table.

<?
function showCode($code) {
    $html = highlight_string($code, true);
    $html = str_replace("n", "", $html);
    $rows = explode("<br />", $html);

    $row_num = array();
    $i = 1;

    foreach($rows as $row) {
        if($i < 10) {
            $i = "0".$i;
        }

        if($i==1) {
            $row_num[] = "<tr><td><code><font color="#000000"><code>$i</code></font>t$row</code></td></tr>";
        }

        if($i!=1) {
            if(is_int($i/2)) {
                $row_num[] = "<tr bgcolor="#F9F9F9"><td><code><font color="#000000">$i</font>t$row</code></td></tr>";
            } else {
                $row_num[] = "<tr><td><code><font color="#000000">$i</font>t$row</code></td></tr>";
            }
        }

        $i++;
    }
    return "<pre>nFilename: <b>$_GET[file]</b>n<table
    style="border:1px #000000 solid">".implode($row_num)."</table></pre>";
}
?>


support at superhp dot de

17 years ago


With this function you can highlight php code with line numbers:

<?php
function highlight_php($string)
{
 
$Line = explode("n",$string);

  for(

$i=1;$i<=count($Line);$i++)
  {
   
$line .= "&nbsp;".$i."&nbsp;<br>";
  }
ob_start();
 
highlight_string($string);
 
$Code=ob_get_contents();
 
ob_end_clean();$header='<table border="0" cellpadding="0" cellspacing="0" width="95%" style="border-style: solid; border-width:1px; border-color: white black black white">
    <tr>
      <td width="100%" colspan="2"  style="border-style: solid; border-width:1px; border-color: white; background-color: #99ccff; font-family:Arial; color:white; font-weight:bold;">Php-Code:</td>
    </tr>
    <tr>
      <td width="3%" valign="top" style="background-color: #99ccff; border-style: solid; border-width:1px; border-color: white;"><code>'
.$line.'</code></td>
      <td width="97%" valign="top" style="background-color: white;"><div style="white-space: nowrap; overflow: auto;"><code>'
;$footer=$Code.'</div></code></td>
    </tr>
  </table>'
;

  return

$header.$footer;
}
?>


peter at int8 dot com

16 years ago


This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet.
<?php highlight_string("<? $var = 15; ?>"); ?>
works, while
<?php highlight_string("$var = 15;"); ?>
does not. This is unforunate for those of use who want to show tiny code snippets, but there you go. Earlier versions of this function did not have this requirement, if I remember correctly.

supremacy2k at gmail dot com

15 years ago


A simplification of functions vanessaschissato at gmail dot com at 17-Oct-2006 05:04.

Since it had trouble keeping the code intact. (It removed /* )

function showCode($code) {
$code = highlight_string($code, true);
$code = explode("<br />", $code);

$i = "1";
foreach ($code as $line => $syntax) {
  echo "<font color='black'>".$i."</font> ".$syntax."<br>";
  $i++;
}
}


tyler dot reed at brokeguysinc dot com

16 years ago


This is a little chunk of code that i use to show the source of a file, i took part of the idea from a example i found on another php function page.

This code takes a php file and highlights it and places a line number next to it.  Great for on the fly debugging.

<?php
// Get a file into an array
$lines = file('index.php');// Loop through our array, show HTML source as HTML source; and line numbers too.
echo('<table border=0 cellpadding=0 cellspacing=0>');
foreach (
$lines as $line_num => $line) {
    echo(
'<tr>');
    echo(
'<td bgcolor = "#cccccc">');
    echo(
'<code>' . ($line_num + 1) . '</code>');
    echo(
'</td>');
    echo(
'<td>');         
   
highlight_string($line);
    echo(
'</td>');
    echo(
'</tr>');
}
?>


zero

17 years ago


In some cases, I found that it's useful to have highlight_string format <code>...</code> inline as part of a paragraph, and other times, as a block for demonstrating multiple lines of code. I made this function to help out.

<?php
   
function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
   
{
        (string)
$highlight = "";
        if (
version_compare(phpversion(), "4.2.0", "<") === 1 )
        {
           
ob_start(); // start output buffering to capture contents of highlight
           
highlight_string($code);
           
$highlight = ob_get_contents(); // capture output
           
ob_end_clean(); // clear buffer cleanly
       
}
        else
        {
           
$highlight=highlight_string($data, true);
        }
## The classes below need to correspond to a stylesheet!
       
if ( $inline === true )
         
$highlight=str_ireplace("<code>","<code class="inline">",$highlight);
        else
         
$highlight=str_ireplace("<code>","<code class="block">",$highlight);

                            if (

$return === true )
        {
            return
$highlight;
        }
        else
        {
            echo
$highlight;
        }
    }
?>


joshuaeasy4u at gmail dot com

9 years ago


<?php
function printCode($source_code)
{
if (
is_array($source_code))
return
false;
$source_code=explode("n",str_replace(array("rn","r"),"n",$source_code));
$line_count=1;
foreach (
$source_code as $code_line)
{
$formatted_code .='<tr><td>'.$line_count.'</td>';
$line_count++;
if (
ereg('<?(php)?[^[:graph:]]',$code_line))
$formatted_code.='<td>'.str_replace(array('<code>','</code>'),'',highlight_string($code_line,true)).'</td></tr>';
else
$formatted_code .='<td>'.ereg_replace('(&lt;?php&nbsp;)+','',str_replace(array('<code>','</code>'),'',highlight_string('<?php '.$code_line,true))).'</td></tr>';
}
return
'<table style="font: 1em Consolas, 'andale mono', ' monotype.com', 'lucida console', monospace;">'.$formatted_code.'</table>';
}
?>

Dmitry S

14 years ago


The simple XML syntax highlighting.

<?php
function xml_highlight($s)
{
    
$s = preg_replace("|<[^/?](.*)s(.*)>|isU","[1]<[2]\1[/2] [5]\2[/5]>[/1]",$s);
    
$s = preg_replace("|</(.*)>|isU","[1]</[2]\1[/2]>[/1]",$s);
    
$s = preg_replace("|<?(.*)?>|isU","[3]<?\1?>[/3]",$s);
    
$s = preg_replace("|="(.*)"|isU","[6]=[/6][4]"\1"[/4]",$s);
    
$s = htmlspecialchars($s);
    
$replace = array(1=>'0000FF', 2=>'808000', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
     foreach(
$replace as $k=>$v)
     {
         
$s = preg_replace("|[".$k."](.*)[/".$k."]|isU","<font color="".$v."">\1</font>",$s);
     }
    return
nl2br($s);
}
?>


How do I change the color of an echo message and center the message in the PHP I’ve written. The line I have is:

echo 'Request has been sent. Please wait for my reply!';

mauris's user avatar

mauris

42.5k15 gold badges98 silver badges131 bronze badges

asked Nov 7, 2009 at 1:49

The Woo's user avatar

0

How about writing out some escape sequences?

echo "33[01;31m Request has been sent. Please wait for my reply! 33[0m";

Won’t work through browser though, only from console ;))

answered Nov 7, 2009 at 1:55

kolypto's user avatar

kolyptokolypto

30k16 gold badges101 silver badges97 bronze badges

4

How about writing out some HTML tags and some CSS if you’re outputting this to the browser?

echo '<span style="color:#AFA;text-align:center;">Request has been sent. Please wait for my reply!</span>';

Won’t work from console though, only through browser.

answered Nov 7, 2009 at 1:50

mauris's user avatar

maurismauris

42.5k15 gold badges98 silver badges131 bronze badges

And if you are using Command line on Windows, download a program ANSICON that enables console to accept color codes. ANSICON is available at https://github.com/adoxa/ansicon/releases

answered Dec 29, 2010 at 12:51

Lukasz Czerwinski's user avatar

0

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."n";
}

echo center('foo');
echo center('bar baz', '=');

answered Aug 18, 2015 at 16:50

Mikkel's user avatar

MikkelMikkel

1,1729 silver badges22 bronze badges

1

Try this

<?php 
echo '<i style="color:blue;font-size:30px;font-family:calibri ;">
      hello php color </i> ';
//we cannot use double quote after echo , it must be single quote.
?>

Gottlieb Notschnabel's user avatar

answered Sep 7, 2014 at 8:01

vithkimly's user avatar

this works for me every time try this.

echo "<font color='blue'>".$myvariable."</font>";

since font is not supported in html5 you can do this

echo "<p class="variablecolor">".$myvariable."</p>";

then in css do

.variablecolor{
color: blue;}

answered Oct 3, 2019 at 3:15

jerryurenaa's user avatar

jerryurenaajerryurenaa

3,2681 gold badge19 silver badges16 bronze badges

3

If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:

echo '<p style="color: red; text-align: center">
      Request has been sent. Please wait for my reply!
      </p>';

answered Nov 7, 2009 at 1:53

Anthony's user avatar

AnthonyAnthony

36k24 gold badges95 silver badges163 bronze badges

How do I change the color of an echo message and center the message in the PHP I’ve written. The line I have is:

echo 'Request has been sent. Please wait for my reply!';

mauris's user avatar

mauris

42.5k15 gold badges98 silver badges131 bronze badges

asked Nov 7, 2009 at 1:49

The Woo's user avatar

0

How about writing out some escape sequences?

echo "33[01;31m Request has been sent. Please wait for my reply! 33[0m";

Won’t work through browser though, only from console ;))

answered Nov 7, 2009 at 1:55

kolypto's user avatar

kolyptokolypto

30k16 gold badges101 silver badges97 bronze badges

4

How about writing out some HTML tags and some CSS if you’re outputting this to the browser?

echo '<span style="color:#AFA;text-align:center;">Request has been sent. Please wait for my reply!</span>';

Won’t work from console though, only through browser.

answered Nov 7, 2009 at 1:50

mauris's user avatar

maurismauris

42.5k15 gold badges98 silver badges131 bronze badges

And if you are using Command line on Windows, download a program ANSICON that enables console to accept color codes. ANSICON is available at https://github.com/adoxa/ansicon/releases

answered Dec 29, 2010 at 12:51

Lukasz Czerwinski's user avatar

0

This is an old question, but no one responded to the question regarding centering text in a terminal.

/**
 * Centers a string of text in a terminal window
 *
 * @param string $text The text to center
 * @param string $pad_string If set, the string to pad with (eg. '=' for a nice header)
 *
 * @return string The padded result, ready to echo
 */
function center($text, $pad_string = ' ') {
    $window_size = (int) `tput cols`;
    return str_pad($text, $window_size, $pad_string, STR_PAD_BOTH)."n";
}

echo center('foo');
echo center('bar baz', '=');

answered Aug 18, 2015 at 16:50

Mikkel's user avatar

MikkelMikkel

1,1729 silver badges22 bronze badges

1

Try this

<?php 
echo '<i style="color:blue;font-size:30px;font-family:calibri ;">
      hello php color </i> ';
//we cannot use double quote after echo , it must be single quote.
?>

Gottlieb Notschnabel's user avatar

answered Sep 7, 2014 at 8:01

vithkimly's user avatar

this works for me every time try this.

echo "<font color='blue'>".$myvariable."</font>";

since font is not supported in html5 you can do this

echo "<p class="variablecolor">".$myvariable."</p>";

then in css do

.variablecolor{
color: blue;}

answered Oct 3, 2019 at 3:15

jerryurenaa's user avatar

jerryurenaajerryurenaa

3,2681 gold badge19 silver badges16 bronze badges

3

If it echoing out to a browser, you should use CSS. This would require also having the comment wrapped in an HTML tag. Something like:

echo '<p style="color: red; text-align: center">
      Request has been sent. Please wait for my reply!
      </p>';

answered Nov 7, 2009 at 1:53

Anthony's user avatar

AnthonyAnthony

36k24 gold badges95 silver badges163 bronze badges

Doctor_Che

0 / 0 / 2

Регистрация: 26.01.2011

Сообщений: 96

1

Не понятно, как изменить цвет текста

25.12.2011, 03:29. Показов 38214. Ответов 1

Метки нет (Все метки)


Пытаюсь изменить цвет текста выводящегося через функцию — выводит черным «Здравствуйте!». При этом при простом выводе — цвет красный «PHP работает!».
Почему так? Как сделать красным во втором случае?

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html> <head>
 <title> №3-3 </title>
 </head> <body> 
 
<?php
 
    $color = "red";
 
    print "<p><font color=$color>PHP работает!</font>";
 
// Приветствие на русском языке
   function Ru() { print "<p><font color=$color>Здравствуйте!</font>"; }
 
$language = "Ru"; // Выбрали русский язык
 
$language();           // Выполнение функции-переменной
 
?>
 </body> </html>

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Maksimchikfull

Веб-мастер

89 / 89 / 19

Регистрация: 11.08.2011

Сообщений: 674

25.12.2011, 03:35

2

Цитата
Сообщение от Doctor_Che
Посмотреть сообщение

Пытаюсь изменить цвет текста выводящегося через функцию — выводит черным «Здравствуйте!». При этом при простом выводе — цвет красный «PHP работает!».
Почему так? Как сделать красным во втором случае?

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html> <head>
 <title> №3-3 </title>
 </head> <body> 
 
<?php
 
    $color = "red";
 
    print "<p><font color=$color>PHP работает!</font>";
 
// Приветствие на русском языке
   function Ru() { print "<p><font color=$color>Здравствуйте!</font>"; }
 
$language = "Ru"; // Выбрали русский язык
 
$language();           // Выполнение функции-переменной
 
?>
 </body> </html>
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html> <head>
 <title> №3-3 </title>
 </head> <body> 
 
<?php
 
    $color = "red";
 
    print "<p><font color='$color'>PHP работает!</font>";
 
// Приветствие на русском языке
   function Ru() { print "<p><font color=$color>Здравствуйте!</font>"; }
 
$language = "Ru"; // Выбрали русский язык
 
$language();           // Выполнение функции-переменной
 
?>
 </body> </html>

Но лутше использовать <span> вместо <font>. И не забывать закрывать тег <p>, он же парный!

PHP
1
echo "<p><span style='$color'>Example</span></p>";



0



Класс PHP для вывода в консоль цветного текста +16

Разработка веб-сайтов, PHP


Рекомендация: подборка платных и бесплатных курсов Smm — https://katalog-kursov.ru/

Делал для себя скрипт для деплоя сайта на продакшен. Для чего нужно было выводить на экран что происходит. И чтобы было нагляднее решил выводить в цвете. Однако не смог найти что-то подходящее. Максимум библиотека выводила цветной текст, но не поддерживала отступы. Поэтому сделал свою библиотеку для этого. Возможно кому-то будет полезно. Небольшая (но функциональная) библиотека для вывода на консоль цветного текста с поддержкой отступов в таком вот виде

Console::indent(2)->color('brown')->bgcolor('magenta')->writeln('Привет Habr!');

  1. Установка
  2. Использование
  3. Отступ
  4. Стили
  5. Логирование
  6. Синтаксический сахар

Установка

Для установки можно воспользоваться composer

composer require shasoft/console

или скачать с github

Использование

Список всех поддерживаемых цветов. Имена колонок — цвета фона, имена строк — цвета текста.
Пример вывода цветного текста

Вывод цветного текста

  • Функция color(значение) — установить цвет текста
  • Функция bgcolor(значение) — установить цвет фона
  • Функция write(значение1, значение2,) — вывести значение на экран. Если значение не является строкой, то оно преобразовывается в строку с помощью php функции var_export(значение,true)
  • Функция reset() — сбросить цвета в значения по умолчанию
  • Функция setDefault() — установить цвета по умолчанию. Значения по умолчанию: цвет фона = black, цвет текста = white
  • Функция enter($resetColor=true). По умолчанию вызов функции сбрасывает цвета в значения по умолчанию. Обратите внимание, что строка не выводится пока не вызвана функция enter(). Это связано с тем, что библиотека поддерживает отступы.
  • Функция writeln() — write()+enter()

use ShasoftConsoleConsole;
// Вывод цветного текста в строке
Console::color('red')->bgcolor('green')->write('Красный текст на зеленом фоне')->enter();
// Вывод цветного текста в строке
Console::color('green')->bgcolor('red')->writeln('Зеленый текст на красном фоне');
// Вывод цветного текста в строке
Console::color('red')->bgcolor('white')->write('Красный текст на белом фоне фоне')->reset()->writeln('Вывод текста цветом по умолчанию');

Отступы

Для работы с отступами служит функция indent(значение отступа[,абсолютное значение]) — если указан второй параметр и он = true, то отступ абсолютный. Иначе отступ относительный. Для получения текущего отступа нужно вызвать функцию indent() без параметров.

Пример:

use ShasoftConsoleConsole;

Console::indent(0,true); // Отступ 0
Console::indent(1)->color('red')->writeln('Отступ 1');
Console::indent(3,true)->color('green')->writeln('Отступ 3');
Console::indent(-1)->color('blue')->writeln('Отступ 2');

К примеру был отступ = 2 indent(1) Отступ = 3
К примеру был отступ = 2 indent(-1) Отступ = 2
К примеру был отступ = 2 indent(10) Отступ = 10
К примеру был отступ = 2 indent(1) Отступ = 1

вывод: Пример вывода с отступом

  • Функция setTabSize(размер табулятора) — задает размер табулятора. По умолчанию = 3
  • Функция setSpace(символ) — задает символ табулятора. По умолчанию = ‘ ‘ (пробел)

функция indent применяется к выводимой СТРОКЕ и значение будет меняться до вызова функции enter(). Т.е. вот этот код выведет строку с отступом 3

Console::indent(0,true)->color('red')->indent(1)->bgcolor('blue')->indent(1)->write('Отступ 3')->indent(1)->enter();

Стили

Можно указать стили. По умолчанию задан стиль ошибок «error»

  • Функция setStyle(имя стиля,цвет текста=null,цвет фон=null) — установить параметры стиля
  • Функция style(имя стиля) — использовать указанный стиль

Пример использования:

Console::indent(1,true)->style("error")->writeln('Какая-то ошибка');

вывод: Пример использования стиля

Логирование

Имеются специальные функции для контроля логирования

  • Функция setLogLevel($value=null) — Установить/получить глобальный уровень логирования. По умолчанию = 0
  • Функция logLevel($value=null) — Установить/получить уровень логирования. По умолчанию = 0

Значения выводятся на экран с помощью функции write() только в случае если текущий уровень логирования меньше-равен глобальноному уровню логирования.

Пример:

Console::setLogLevel(0)->logLevel(1)->writeln('Не выведется, так как уровень логирования = 1 который больше 0');
Console::setLogLevel(2)->logLevel(1)->writeln('Выведется, так как уровень логирования = 1 который меньше-равен 2');
Console::setLogLevel(2)->logLevel(3)->write('Этот текст не выведется')->logLevel(1)->write('Текст на экране')->enter();

Синтаксический сахар

Чтобы не писать color(‘red’)->bgcolor(‘green’) можно писать в коротком виде

Console::red()->bg_green()->writeln('Строка красного цвета на зеленом фоне.');

Цвет фона можно задавать функцией без подчеркивания. Однако оно визуально отделяет цвет от префикса и, на мой взгляд, весьма удобна.

Страница библиотеки

upd: раз уж мне указали на ошибку в имени функции ident вместо indent, то я её исправил чтобы не смущать тех, кто знает английский хорошо :)

За последние 24 часа нас посетили 11235 программистов и 1041 робот. Сейчас ищет 321 программист …

  1. Здравствуйте! Как изменить цвет, скажем, к примеру, элементу массива?


  2. Gromo

    Gromo
    Активный пользователь

    С нами с:
    24 май 2010
    Сообщения:
    2.786
    Симпатии:
    2
    Адрес:
    Ташкент

    addask
    ты случаем не путаешь html и php ?

  3. да вроде не особо. Хотя мб на правильно выразился, мне нужно в пхп скрипте изменить цвет элемента массива, а с помощью чего, не важно


  4. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    Gromo
    ты еще не знаешь, что каждый элемент массива имеет цвет
    а так же форму, вкус, запах и срок годности


  5. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    addask
    твой вопрос совершенно некорректен. Массив — это набор переменных. Переменная имеет имя и хранит данные.


  6. Brajt

    Brajt
    Активный пользователь

    С нами с:
    20 ноя 2010
    Сообщения:
    86
    Симпатии:
    0

    addask, тебе наверно css нужна (каскадная таблица стилей)

  7. воо шутники то =) Согласен херово я высказался, вообщем тексту надо поменять цвет, тексту.

    А по корявому я сказал, потому как текст я буду брать из массива по типу: $Arr = array («if»,»else»…);


  8. YSandro

    С нами с:
    7 апр 2011
    Сообщения:
    2.523
    Симпатии:
    2

    addask, так ведь тексту тоже невозможно поменять цвет! Текст — это последовательность символов, и только.
    Возможно (приходится догадываться), ты хочешь вывести текст в таблицу на веб странице, и хочешь, чтобы в разных ячейках был разный цвет текста?
    Если так, то цвет можно вывести
    <td style=»color:#ee0000″>красный текст</td>
    Тогда браузер «покрасит» текст в этой ячейке, т.к. в стиле указан код цвета. Но это забота браузера — подкрашивать. В php ты можешь хранить/генерировать коды цвета и выводить в нужном виде в браузер/файл.


  9. igordata

    Команда форума
    Модератор

    С нами с:
    18 мар 2010
    Сообщения:
    32.415
    Симпатии:
    1.768


  10. titch

    titch
    Активный пользователь

    С нами с:
    18 дек 2010
    Сообщения:
    847
    Симпатии:
    0


  11. Dima4321

    Dima4321
    Активный пользователь

    С нами с:
    1 апр 2009
    Сообщения:
    683
    Симпатии:
    0

    1. echo ‘<b>’.$array[$i].‘</b><br>’;

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить цвет текста listview
  • Как изменить цвет текста javafx
  • Как изменить цвет текста coreldraw
  • Как изменить цвет текста adobe premiere pro
  • Как изменить цвет тегов

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии