how to colorize php code

i have the below code
---------------------------------------
<?php

  /*

  These classes are used for highlighting, happy css-ing:

  .phpdefault { color:#0000BB; font-weight: bold;}
  .phpkeyword { color:#007700; font-weight: bold;}
  .phpstring  { color:#DD0000; font-weight: normal;}
  .phpcomment { color:#FF8000; font-weight: normal;}

  */

/**
 * Highlights PHP-source snippets with and without php-tags, inserts class definitions on request
 *
 * Strips <code> and <span color:black>, removes empty spans
 *
 * @param string $source Source to highlight
 * @param boolean $classes, true links source elements to classes
 * @return string
 */
function php_highlight($source, $classes = false)
{
  if (version_compare( phpversion(), "5.0.0", "<")) return "PHP 5 required";

  $r1 = $r2 = '##';

  // adds required PHP tags (at least with vers. 5.0.5 this is required)
  if ( strpos($source,' ?>') === false ) // xml is not THAT important ;-)
  {
    $source = "<?php ".$source." ?>";
    $r1 = '#&lt;\?.*?(php)?.*?&nbsp;#s';
    $r2 = '#\?&gt;#s';
  }
  elseif (strpos($source,'<? ') !== false)
  {
    $r1 = '--';
    $source = str_replace('<? ','<?php ',$source);
  }

  $source = highlight_string($source,true);

  if ($r1 =='--') $source = preg_replace('#(&lt;\?.*?)(php)?(.*?&nbsp;)#s','\\1\\3',$source);

  $source = preg_replace (array ( '/.*<code>\s*<span style="color: #000000">/',    //
                                  '#</span>\s*</code>#',                          //  <code><span black>
                                  $r1, $r2,                 // php tags
                                  '/<span[^>]*><\/span>/'   // empty spans
                                ),'',$source);

  if ($classes) $source = str_replace( array('style="color: #0000BB"','style="color: #007700"',
                                         'style="color: #DD0000"','style="color: #FF8000"'),
                                   array('class="phpdefault"','class="phpkeyword"',
                                         'class="phpstring"','class="phpcomment"',),$source);

  return $source;
}

$print_code = <<<PRINT_CODE
    // version:

  function mysql_tree_add($name, $parentName = "") {
      $sql_pe = "SELECT * FROM nested_category WHERE name='$parentName'";
      $q = mysql_query($sql_pe) or die(mysql_error());
      if(mysql_num_rows($q) == 0) {
            Echo $name.' must be parent<BR>';
      }else{
            echo "adding sub ".$name. ' to parent '.$parentName.'<BR>';
            $pe = mysql_fetch_assoc($q);
      }

      //now update the rows
      mysql_query("UPDATE nested_category SET rgt=rgt+2 WHERE rgt>{$pe['rgt']}-1") or die(mysql_error());
      mysql_query("UPDATE nested_category SET lft=lft+2 WHERE lft>{$pe['rgt']}-1") or die(mysql_error());
      //now add the item
      mysql_query("INSERT INTO nested_category (`name`,`lft`,`rgt`) VALUES ('$name',{$pe['rgt']},{$pe['rgt']}+1)") or die(mysql_error());
  }
PRINT_CODE;


echo '<p>Some tests:</p><p>';
echo php_highlight('<?php $test = new func("Text"); /* regular tags, use classes */ ?>',true),'<br />';
echo 'Inline code: ',php_highlight('<? $test = new func("Text"); /* short tags */ ?>'),
     ' works without or ',php_highlight('define (\'WITH_CLASSES\',\' too\'); /* no tags */',true),'<br />';
echo php_highlight('$test = new func("Text"); /* no tags, no classes */'),'<br />';
echo '</p><p>You are running PHP: '.phpversion().'</p>';
echo php_highlight($print_code);
?>
its outputting
Some tests:

<?php $test = new func("Text"); /* regular tags, use classes */ ?>
Inline code: <? $test = new func("Text"); /* short tags */ ?> works without or define ('WITH_CLASSES',' too'); /* no tags */
$test = new func("Text"); /* no tags, no classes */

You are running PHP: 5.1.4
    // version:

  function mysql_tree_add(,  = "") {
       = "SELECT * FROM nested_category WHERE name=''";
       = mysql_query() or die(mysql_error());
      if(mysql_num_rows() == 0) {
          Echo .' must be parent<BR>';
      }else{
            echo "adding sub ".. ' to parent '..'<BR>';
             = mysql_fetch_assoc();
      }

      //now update the rows
      mysql_query("UPDATE nested_category SET rgt=rgt+2 WHERE rgt>-1") or die(mysql_error());
      mysql_query("UPDATE nested_category SET lft=lft+2 WHERE lft>-1") or die(mysql_error());
      //now add the item
      mysql_query("INSERT INTO nested_category (`name`,`lft`,`rgt`) VALUES ('',,+1)") or die(mysql_error());
  }
--------------------------------------------


please note on this lines
      $sql_pe = "SELECT * FROM nested_category WHERE name='$parentName'";
      $q = mysql_query($sql_pe) or die(mysql_error());

the $sql_pe and the $q are missing as well as some others too
is there a better way to do this?

i really like the way it allows for inline statements and i want to be able to pass chucks to it too

thank you in advance for any code and help you may provide
JohnnyAsked:
Who is Participating?
 
AlexanderREnterprise Web DeveloperCommented:
You probably thought of this before, but why cant you do
str_replace("'", "\'", $print_code) somewhere before your echos.
$print_code is just a regular string as far as i can see you should be able to perform any kind changes to it.
Or are there other problems?

Sorry if i am being dense.
0
 
DelTremeCommented:
The heredoc syntax also inserts the contents of $sql_pe and $q into $print_code.

This can be made visible by setting them before:
//(...)
  return $source;
}
$q = 'I will be inserted by heredoc';     # added
$print_code = <<<PRINT_CODE
    // version:
//(...)
0
 
JohnnyAuthor Commented:
im looking to take strings and colorize them.. how do i do this then.. setting the $vars is NOT an option as this will be used in articles to display code

0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
DelTremeCommented:
I'd recommend putting the source you want displayed in a seperate file, source.php for instance, and then loading it this way:

$print_code = file_get_contents('source.php');

That way you do not have to alter the source code before displaying it, and you have your colorize script and source data seperated.

Another way would be using single quotes and escaping the single quotes you already use:

$print_code = '
    // version:

  function mysql_tree_add($name, $parentName = "") {
      $sql_pe = "SELECT * FROM nested_category WHERE name=\'$parentName\'";
      $q = mysql_query($sql_pe) or die(mysql_error());
      if(mysql_num_rows($q) == 0) {
            Echo $name.\' must be parent<BR>\';
      }else{
            echo "adding sub ".$name. \' to parent \'.$parentName.\'<BR>\';
            $pe = mysql_fetch_assoc($q);
      }

      //now update the rows
      mysql_query("UPDATE nested_category SET rgt=rgt+2 WHERE rgt>{$pe[\'rgt\']}-1") or die(mysql_error());
      mysql_query("UPDATE nested_category SET lft=lft+2 WHERE lft>{$pe[\'rgt\']}-1") or die(mysql_error());
      //now add the item
      mysql_query("INSERT INTO nested_category (`name`,`lft`,`rgt`) VALUES (\'$name\',{$pe[\'rgt\']},{$pe[\'rgt\']}+1)") or die(mysql_error());
  }
';
0
 
JohnnyAuthor Commented:
i thought of that printing it to a file...

id rather not do that as it would fill up alot of space. but it maybe the only way.

i had escaped the quotes manually for my testing and that DOES work. but to do that all the time in code would be cumbersome at best.

again reverting to saving a file i guess i can parse it and save it to a fill then read the fille back to display it.

let me think a bit about this, and see if anyone else has a suggestion too..thanks for the reply DelTreme:
0
 
AlexanderREnterprise Web DeveloperCommented:
If you want to print to a file you might as well print to a   .phps file. When apache sees phps file it automatically does all the nice looking code highlights.  You can configure how you want it from php.ini or use php code to overide the defaults if you have no access to php.ini. This way you dont have to do any mods of your own to to code highliting.

Thats if i understand your purpose correctly.

Also, what exactly does all of that code do? There are some queries that doe something (???) and then you want to display php source on screen (sorry am in hurry so dont have time to go through it right now, but when come back, hope to give something usefull)
0
 
JohnnyAuthor Commented:
Ive been playing with the code some and i came up with

http://dragon-software.info/ee/print_code_color2.php

my problem is i have to escape \' if i don't it does not display right alternately it does not display $vars correctly and there missing.

id like to know how to send the text to be color coded at will, as there will be articles posted id like to colorize the code, and will passing the strings to the function with this code snips to be colorized.

i thought that <<< Begin_End  ..... Begin_End would do it and allow for text inside the string to be parsed as is, but as you can see it does not do that in the org posted question.

i need to be able to pass to echo php_highlight($print_code); the $print_code var with the text i want to parse, preformated or prechanged so its automatically parsed if need be for \' and or anything else that needs to be done. as this will be a posted page on the web site and will not be able to manually make changes to fix this problem.

I'm not trilled about saving the code to a file then parsing the files info each time it needs to be displayed to the browser, i did think of saving the code I'm mysql and see if it parses that way correctly, but i have not tried that yet. would saving it in mysql work like saving it to a file would it have to be saved as binary or with htmlentities() {spelling on that function}

please note: i changed the output on the displayed coloring to simulate HTML output as the function now inserts line numbers and can use CSS to parse HTML,JAVA,PHP and other code snips, something I'm going to want to do in the future HTML,PHP and JavaScript are parsing colors with that script now.

I know a script called i believe GENSHI or something like that does all this too, but i want to simplify it a bit and output the display the way i want it.

also NOTE: i was able to parse the info in the org question by simply using the same code and in the $print_code var adding \' to each ' that was not inside the vars correct outlining ' (quotes)
and it rendered perfectly after that with the vars intact too

hope this long winded post helps clear a few things up a bit
(also I'm not locked into anything right now I'm flexible on how to get this all to work even rewriting the color parser, although id like to post the one i have now if thats going to be done to show the way i have done the rest of the added capability's

0
 
JohnnyAuthor Commented:
nope no joy AlexanderR:

it still the same problem it omits some of the vars and now it really messes it up as there are other ' that are not affecting the output that are now being a problem
lines 9 and 17 you can see this really well

GRRRR!!!


1     // version:
2
3   function mysql_tree_add(,  = "") {
4        = "SELECT * FROM nested_category WHERE name=\'\'";
5        = mysql_query() or die(mysql_error());
6       if(mysql_num_rows() == 0) {
7           Echo .' must be parent<BR>\';
8       }else{
9             echo "adding sub ".. \' to parent \'..\'<BR>\';
10              = mysql_fetch_assoc();
11       }
12
13       //now update the rows
14       mysql_query("UPDATE nested_category SET rgt=rgt+2 WHERE rgt>-1") or die(mysql_error());
15       mysql_query("UPDATE nested_category SET lft=lft+2 WHERE lft>-1") or die(mysql_error());
16       //now add the item
17       mysql_query("INSERT INTO nested_category (`name`,`lft`,`rgt`) VALUES (\'\',,+1)") or die(mysql_error());
18   }  

--------------------------------------
please see next post on whats going on
0
 
JohnnyAuthor Commented:
--------------------------- snip version 1 ----------------
$print_code = <<<PRINT_CODE
    // version:

  function mysql_tree_add($name, $parentName = "") {
      $sql_pe = "SELECT * FROM nested_category WHERE name='$parentName'";
      $q = mysql_query($sql_pe) or die(mysql_error());
      if(mysql_num_rows($q) == 0) {
            Echo $name.' must be parent<BR>';
     }else{
            echo "adding sub ".$name. ' to parent '.$parentName.'<BR>';
            $pe = mysql_fetch_assoc($q);
      }

      //now update the rows
      mysql_query("UPDATE nested_category SET rgt=rgt+2 WHERE rgt>{$pe['rgt']}-1") or die(mysql_error());
      mysql_query("UPDATE nested_category SET lft=lft+2 WHERE lft>{$pe['rgt']}-1") or die(mysql_error());
      //now add the item
      mysql_query("INSERT INTO nested_category (`name`,`lft`,`rgt`) VALUES ('$name',{$pe['rgt']},{$pe['rgt']}+1)") or die(mysql_error());
  }
PRINT_CODE;

$print_code = str_replace("'", "\'", $print_code);
php_highlight($print_code,1,true,"",true)."";
----------------- end snip version 1 -------------------------------

----------------- snip version 2 ----------------------------
php_highlight('    // version:

  function mysql_tree_add($name, $parentName = "") {
      $sql_pe = "SELECT * FROM nested_category WHERE name=\'$parentName\'";
      $q = mysql_query($sql_pe) or die(mysql_error());
      if(mysql_num_rows($q) == 0) {
            Echo $name.\' must be parent<BR>\';
      }else{
            echo "adding sub ".$name. \' to parent \'.$parentName.\'<BR>\';
            $pe = mysql_fetch_assoc($q);
      }

      //now update the rows
      mysql_query("UPDATE nested_category SET rgt=rgt+2 WHERE rgt>{$pe[\'rgt\']}-1") or die(mysql_error());
      mysql_query("UPDATE nested_category SET lft=lft+2 WHERE lft>{$pe[\'rgt\']}-1") or die(mysql_error());
      //now add the item
      mysql_query("INSERT INTO nested_category (`name`,`lft`,`rgt`) VALUES (\'$name\',{$pe[\'rgt\']},{$pe[\'rgt\']}+1)") or die(mysql_error());
  }',1,true,"",true)."";

------------------ end snip version 2 --------------


now snip version 1 does not work. snip version 2 does work fine.
could it be how the parsing is going on in the php_highlight() function?

or should i try and echo this all to a file and see what happens to it, or mysql field?

or do we have a solution to the problem!
0
 
JohnnyAuthor Commented:
dragon-software.info\ee\print_code_color2.phps
theres the code encase anyone wants to play with it..please fell free to change things and fix things to make it work, even if you want to rewrite it too.

thanks for any help
0
 
JohnnyAuthor Commented:
sorry (copy and paste in windows with firefox that converts to this)
http://dragon-software.info/ee/print_code_color2.phps
0
 
AlexanderREnterprise Web DeveloperCommented:
One last question (hope its last).
Where exactly is that code-to-be-highlighted comming from? Is it one of those things where on a forum user types in some codes in a text box and then when its posted and you look at the submitted comment it comes out with that highlights?
0
 
SissonCommented:
ob_start();
show_source("path/to/file");
$fc = ob_get_clean();

$fc contains your file's content.  from there you will be able to preg_replace the <color> and <font> tags into more reliable <span> tags.
The good thing is that it is already colored and niceified for you!
0
 
JohnnyAuthor Commented:
AlexanderR:

yes but in an articles site bbcode of [code-PHP]  blah blah blah [/code]  will do the parse for php color code.
etc
although i have to rewrite that so that more prams can be sent to it as we now have more adjustments to the display (ie line numbers etc)

we have the wysiwyg interface. and changed the [code][/code] tags.

just need to fix this problem now.
-----------------------------------
Sisson:

quote from post  ID: 19663548
{see above for id post}

[quote]
I'm not trilled about saving the code to a file then parsing the files info each time it needs to be displayed to the browser
[/quote]

there will be lets take a posting to an article
lets say 10 different code snips to display
like this post http://us3.php.net/manual/en/function.highlight-file.php
lets say thats on the site I'm trying to do. (i want more flexibility then the parse <?PHP ?> tags they have in posts)
but it has literately 10 different files I'd have to associate to the one article for that page alone. let alone little code snips (one liners etc)
so not only would i have LOTS of files but id have to track each one and store the article and the snips too separately. a logistics nightmare (although mysql and a few fields i can see that happening(may have to go that route - don't want to but may have to again))
getting the picture
if i can just have the wysiwyg interface parse this info id be all set.
but thanks for the suggestion
0
 
AlexanderREnterprise Web DeveloperCommented:
I know you wont like this answer but today must be a bad for me. I am not getting anywhere. For some reason it comments out all " making the output look useless.

I came across a PHP Pear function text_highlighter
http://pear.php.net/package/Text_Highlighter
It seems pretty customizable.  If not i am sure something simple as font sizes and colors can be changed from the packages source php code.  And it supports multiple languages.

There is also a built in function in php called highlight_string. It produces some interesting results!!, but less customizable.

Some other info can be taken from http://www.sitepoint.com/article/highlight-source-code-php

If you cant get anywhere with yours, i suggest you use PHPs own highlight thing.
0
 
AlexanderREnterprise Web DeveloperCommented:
http://bs.php.net/manual/en/function.highlight-string.php
look down at comments. first 3 could be usefull.
But it comments out ' at the worst places, making it look useless again. May be PEAR thing is better.
OK, no more posts from me unless its something working.
0
 
JohnnyAuthor Commented:
http://hdragonsoftware.info/test/geshi/contrib/expand.php?file=word_filter.vbs&discription=Filter%20Script&info=Created%20by%20Unknown&hight=27
(i own the above linked site)
the above link comes from here
http://hdragonsoftware.info/Downloads.php (the 'Click Here for File Contents' link)
using GeSHi 1.0.7.13

http://qbnz.com/highlighter/demo.php

now GeSHi works ok..and i may integrate it into the site but i was looking for a better way of my own.

i got it all to work one day, it was hard to do, see above top link for what i made GeSHi do for me.
if you click on the plus sign it expands.

but to in corp that into the new site maybe more hassle then its worth.

and AlexanderR: always keep posting stuff it may trigger an idea or a solution.
thanks for the help so far.. theres gotta be a way heck allot of article pages out there use color.

i think i should start to see if i can play with the mysql fields and see if i can get it to parse that way. (storing the info and parsing the results. i need to think of this from the article side of how to display the article and how to get the code blocks(snips) in the article.
0
 
AlexanderREnterprise Web DeveloperCommented:
But if this is an article base system, how else were you going to keep users posts and codes they submit without recording it in database??
0
 
JohnnyAuthor Commented:
i was gonna write it all down on paper and hand deliver the info to EVERY person on the planet...!!!!

can we say DUH!.

ok i MUST be tired it dawned on me that the info will be IN a database but not that its stored in the database, if that makes sense.

so i maybe going at this wrong then.

let me do a few tests and see if i can get this all to work, most likely on weekend or Monday.
i will advise after i try and get it to save in the database.
0
 
AlexanderREnterprise Web DeveloperCommented:
Sorry for a stupid question.

Just that at the beginning it did not seem like a multiuser post/article management database, but just having a few files source code displayed in browser.

Anyways, if these codes are going to be submitted and reviewed by online users, storying the entire code together with the post to a database is the only way i see it.  So all that php code had to be going to database from the beginning.  Of course that wouldnt solve our current problem but that will give us idea of whats on our way.  For instance when that code gets into DB mysql_real_escape_string gets rid of quite a lot of ' kind of things that would otherwise break the query. It does the same thing or backward action uppon retrieval.  So that alone will give a totally different scenario rather than just typing it in a string manually as in the example provided.

I hope everyone is on the same page now and now more missunderstandings will occure.  I will try to do some tests on that mysql note
0
 
JohnnyAuthor Commented:
ive moved on to dokuwiki it does what i want all ready without having to customize the code

AlexanderR:
im giving you the points as you tryed to help
0
 
JohnnyAuthor Commented:
i ment this answer
AlexanderR:
But if this is an article base system, how else were you going to keep users posts and codes they submit without recording it in database??
0
 
AlexanderREnterprise Web DeveloperCommented:
Not the best way i like to receive points, but thank :)
0
 
JohnnyAuthor Commented:
you pointed out the problem..thats an answer non the less
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.