PHP has a function called get_meta_tags which can read meta tags of HTML files. However, as far as I know there is no standard way to define meta tags for PHP files. The de facto solution seems to be to add comment to the top of the file like so:
<?php
# Author: Ood
# Description: Hello World
?>
Is there any way to read these "meta tags" with PHP similar to the way get_meta_tags works using the default PHP library? Preferably without parsing the entire file with file_get_contents followed by a regex for best performance. If not, maybe someone knows of a better solution to add meta data capabilities to PHP files. Thanks in advance!
In our project we are happy with the standard JavaDoc that was adopted by PHPDoc using the #field syntax as you might know it from any PHP function or class definition. This is pretty fine readable using the PHPDocumenter.
In our adoption we use the very first multi-line comment, ie anyting between /** and closing tag */, using the JavaDoc style to describe all the details about the current script.
So to adopt your example in our project we would have following syntax:
<?php
/**
* #author Ood
* #desc Hello World
*/
Of course you may end up with your custom function reading the beginning of the php file parsing just the very first multi-line comment to get the script description aka meta tags.
Sometimes in my code I like to comment out a block of code for temporary use/reference etc eg:
/*
blah
*/
But it's a minor annoyance that if I then want to go and insert a line inside that block, when I click enter, it will automatically put a * on the next line as though I were doing a DocBlock. This happens on every enter key:
/*
blah<enter pressed here>
*
*/
Now I would have thought this 'auto-formatting' should only take place if the opening comment is using the format /** (two stars). Multi line comments were around a long time before DocBlocks, so I'm not sure why it forces these "old school" standard straight forward /* */ comments to have fancy unwanted extra DocBlock *'s!
So is there a way to:
a) Ideally - only have that formatting take place if the opening tag is /**
b) Or if it can't differentiate between /* and /**, is there a way to disable the auto-comment-formatting entirely?
Cheers
I ended up entering this as a Netbeans bug in their Bugzilla and they have now fixed the issue. They did this VERY Quickly I should add - within 12 hours - kudos to them. From what I can make out it looks like it will be included in Netbeans 7.4 release. Gotta love Open Source! :)
Job details here:
https://netbeans.org/bugzilla/show_bug.cgi?id=230814
select your code and press ctrl+? It will comment with double all lines selected
Is there any way to show the current PHP function or class name in the VIM command line? I found a plugin for showing C function names in the status line but it does not work for PHP and in any case I prefer the command line be used to save valuable vertical lines.
Thanks.
EDIT
While looking for something completely unrelated in TagList's help I've just found these two functions:
Tlist_Get_Tagname_By_Line()
Tlist_Get_Tag_Prototype_By_Line()
Adding this in my statusbar works beautifully:
%{Tlist_Get_Tagname_By_Line()}
Also, did you read the Vim Wiki? It has a bunch of tips trying to adress the same need. There is also this (untested) plugin.
ENDEDIT
If you are short on vertical space maybe you won't mind using a bit of horizontal space?
TagList and TagBar both show a vertical list of the tags used in the current buffer (and other opened documents in TagList's case) that you can use to navigate your code.
However, I'm not particularly a fan of having all sorts of informations (list of files, VCS status, list of tags, list of buffers/tabs…) displayed at all times: being able to read the name of the function you are in is only useful when you actually need to know it, otherwise it's clutter. Vim's own [{ followed by <C-o> are enough for me.
I don't know anything about PHP, and I'm not trying to step on anyone's toes, but having looked at some PHP code I came up with this function which I think takes a simpler approach than the plugins that have been mentioned.
My assumpmtion is that PHP functions are declared using the syntax function MyFunction(){} and classes declared using class MyClass{} (possibly preceded by public). The following function searches backwards from the cursor position to find the most recently declared class or function (and sets startline). Then we search forward for the first {, and find the matching }, setting endline. If the starting cursor line is inbetween startline and endline, we return the startline text. Otherwise we return an empty string.
function! PHP_Cursor_Position()
let pos = getpos(".")
let curline = pos[1]
let win = winsaveview()
let decl = ""
let startline = search('^\s*\(public\)\=\s*\(function\|class\)\s*\w\+','cbW')
call search('{','cW')
sil exe "normal %"
let endline = line(".")
if curline >= startline && curline <= endline
let decl = getline(startline)
endif
call cursor(pos)
call winrestview(win)
return decl
endfunction
set statusline=%{PHP_Cursor_Position()}
Because it returns nothing when it is outside a function/class, it does not display erroneous code on the statusline, as the suggested plugin does.
Of course, I may well be oversimplifying the problem, in which case ignore me, but this seems like a sensible approach.
I am about writing own simple syntax highlighter in PHP. I've done basic algorithm based on regular expressions and string replacement, but what I really don't know is way how to disable replacing keywords which are commented.
For example:
/**
* Some class
*
* #property-read $foo
*/
class Test
{
private $foo;
public function __construct()
{
}
}
Now my solution simply highlight defined keywords (like class or variables) but also those which are commented.
Any solution for this problem?
Why not use PHP's tokenizer to do the job for you? That way, your syntax highlighter will parse the PHP code the exact same way the Zend Engine does, which is probably going to give you a lot better results than a regular expression.
Why not borrow lessons from how vi or vim already does this? long back I remember for some custom tag based language we developed, we wanted syntax highlighting in VI and VIM , that is when we changed few .vi sort of configuration files where we mentioned, all the meta data like which color to what kind of tag, what are tags possible etc.
Looking more into how vi or vim or any text editor does this might be more helpful!
You could exclude the commented lines by this logic:
if line starts with /** disable highlight
if next line starts with * do nothing and check next line
if line starts with */ reenable highlight
Just a quick guess and can be defined more precise, but should work as a logic.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm searching for a PHP syntax highlighting engine that can be customized (i.e. I can provide my own tokenizers for new languages) and that can handle several languages simultaneously (i.e. on the same output page). This engine has to work well together with CSS classes, i.e. it should format the output by inserting <span> elements that are adorned with class attributes. Bonus points for an extensible schema.
I do not search for a client-side syntax highlighting script (JavaScript).
So far, I'm stuck with GeSHi. Unfortunately, GeSHi fails abysmally for several reasons. The main reason is that the different language files define completely different, inconsistent styles. I've worked hours trying to refactor the different language definitions down to a common denominator but since most definition files are in themselves quite bad, I'd finally like to switch.
Ideally, I'd like to have an API similar to CodeRay, Pygments or the JavaScript dp.SyntaxHighlighter.
Clarification:
I'm looking for a code highlighting software written in PHP, not for PHP (since I need to use it from inside PHP).
Since no existing tool satisfied my needs, I wrote my own. Lo and behold:
Hyperlight
Usage is extremely easy: just use
<?php hyperlight($code, 'php'); ?>
to highlight code. Writing new language definitions is relatively easy, too – using regular expressions and a powerful but simple state machine. By the way, I still need a lot of definitions so feel free to contribute.
[I marked this answer as Community Wiki because you're specifically not looking for Javascript]
http://softwaremaniacs.org/soft/highlight/ is a PHP (plus the following list of other languages supported) syntax highlighting library:
Python, Ruby, Perl, PHP, XML, HTML, CSS, Django, Javascript, VBScript, Delphi, Java, C++, C#, Lisp, RenderMan (RSL and RIB), Maya Embedded Language, SQL, SmallTalk, Axapta, 1C, Ini, Diff, DOS .bat, Bash
It uses <span class="keyword"> style markup.
It has also been integrated in the dojo toolkit (as a dojox project: dojox.lang.highlight)
Though not the most popular way to run a webserver, strictly speaking, Javascript is not only implemented on the client-side, but there are also Server-Side Javascript engine/platform combinations too.
I found this simple generic syntax highlighter written in PHP here and modified it a bit:
<?php
/**
* Original => http://phoboslab.org/log/2007/08/generic-syntax-highlighting-with-regular-expressions
* Usage => `echo SyntaxHighlight::process('source code here');`
*/
class SyntaxHighlight {
public static function process($s) {
$s = htmlspecialchars($s);
// Workaround for escaped backslashes
$s = str_replace('\\\\','\\\\<e>', $s);
$regexp = array(
// Comments/Strings
'/(
\/\*.*?\*\/|
\/\/.*?\n|
\#.[^a-fA-F0-9]+?\n|
\<\!\-\-[\s\S]+\-\-\>|
(?<!\\\)".*?(?<!\\\)"|
(?<!\\\)\'(.*?)(?<!\\\)\'
)/isex'
=> 'self::replaceId($tokens,\'$1\')',
// Punctuations
'/([\-\!\%\^\*\(\)\+\|\~\=\`\{\}\[\]\:\"\'<>\?\,\.\/]+)/'
=> '<span class="P">$1</span>',
// Numbers (also look for Hex)
'/(?<!\w)(
(0x|\#)[\da-f]+|
\d+|
\d+(px|em|cm|mm|rem|s|\%)
)(?!\w)/ix'
=> '<span class="N">$1</span>',
// Make the bold assumption that an
// all uppercase word has a special meaning
'/(?<!\w|>|\#)(
[A-Z_0-9]{2,}
)(?!\w)/x'
=> '<span class="D">$1</span>',
// Keywords
'/(?<!\w|\$|\%|\#|>)(
and|or|xor|for|do|while|foreach|as|return|die|exit|if|then|else|
elseif|new|delete|try|throw|catch|finally|class|function|string|
array|object|resource|var|bool|boolean|int|integer|float|double|
real|string|array|global|const|static|public|private|protected|
published|extends|switch|true|false|null|void|this|self|struct|
char|signed|unsigned|short|long
)(?!\w|=")/ix'
=> '<span class="K">$1</span>',
// PHP/Perl-Style Vars: $var, %var, #var
'/(?<!\w)(
(\$|\%|\#)(\->|\w)+
)(?!\w)/ix'
=> '<span class="V">$1</span>'
);
$tokens = array(); // This array will be filled from the regexp-callback
$s = preg_replace(array_keys($regexp), array_values($regexp), $s);
// Paste the comments and strings back in again
$s = str_replace(array_keys($tokens), array_values($tokens), $s);
// Delete the "Escaped Backslash Workaround Token" (TM)
// and replace tabs with four spaces.
$s = str_replace(array('<e>', "\t"), array('', ' '), $s);
return '<pre><code>' . $s . '</code></pre>';
}
// Regexp-Callback to replace every comment or string with a uniqid and save
// the matched text in an array
// This way, strings and comments will be stripped out and wont be processed
// by the other expressions searching for keywords etc.
private static function replaceId(&$a, $match) {
$id = "##r" . uniqid() . "##";
// String or Comment?
if(substr($match, 0, 2) == '//' || substr($match, 0, 2) == '/*' || substr($match, 0, 2) == '##' || substr($match, 0, 7) == '<!--') {
$a[$id] = '<span class="C">' . $match . '</span>';
} else {
$a[$id] = '<span class="S">' . $match . '</span>';
}
return $id;
}
}
?>
Demo: http://phpfiddle.org/lite/code/1sf-htn
Update
I just created a PHP port of my own JavaScript generic syntax highlighter here → https://github.com/taufik-nurrohman/generic-syntax-highlighter/blob/master/generic-syntax-highlighter.php
How to use:
<?php require 'generic-syntax-highlighter.php'; ?>
<pre><code><?php echo SH('<div class="foo"></div>'); ?></code></pre>
It might be worth looking at Pear_TextHighlighter (documentation)
I think it won't by default output html exactly how you want it, but it does provide extensive capabilities for customisation (i.e. you can create different renderers/parsers)
I had exactly the the same problem but as I was very short on time and needed really good code coverage I decided to write a PHP wrapper around Pygments library.
It's called PHPygmentizator. It's really simple to use. I wrote a very basic manual. As PHP is Web Development language primarily, I subordinated the structure to that fact and made it very easy to implement in almost any kind of website.
It supports configuration files and if that isn't enough and somebody needs to modify stuff in the process it also fires events.
Demo of how it works can be found on basically any post of my blog which contains source code, this one for example.
With default config you can just provide it a string in this format:
Any text here.
[pygments=javascript]
var a = function(ar1, ar2) {
return null;
}
[/pygments]
Any text.
So it highlights code between tags (tags can be customized in configuration file) and leaves the rest untouched.
Additionally I already made a Syntax recognition library (it uses algorithm which would probably be classified as Bayesian probability) which automatically recognizes which language code block is written in and can easily be hooked to one of PHPygmentizator events to provide automatic language recognition. I will probably make it public some time this week since I need to beautify the structure a bit and write some basic documentation. If you supply it with enough "learning" data it recognizes languages amazingly well, I tested even minified javascripts and languages which have similar keywords and structures and it has never made a mistake.
Another option is to use the GPL Highlight GUI program by Andre Simon which is available for most platforms. It converts PHP (and other languages) to HTML, RTF, XML, etc. which you can then cut and paste into the page you want. This way, the processing is only done once.
The HTML is also CSS based, so you can change the style as you please.
Personally, I use dp.SyntaxHighlighter, but that uses client side Javascript, so it doesn't meet your needs. It does have a nice Windows Live plugin though which I find useful.
A little late to chime in here, but I've been working on my own PHP syntax highlighting library. It is still in its early stages, but I am using it for all code samples on my blog.
Just checked out Hyperlight. It looks pretty cool, but it is doing some pretty crazy stuff. Nested loops, processing line by line, etc. The core class is over 1000 lines of code.
If you are interested in something simple and lightweight check out Nijikodo:
http://www.craigiam.com/nijikodo
Why not use PHP's build-in syntax highlighter?
http://php.net/manual/en/function.highlight-string.php
PHP Prettify Works fine so far, And has more customization than highlight_string
Krijn Hoetmer's PHP Highlighter provides a completely customizable PHP class to highlight PHP syntax. The HTML it generates, validates under a strict doctype, and is completely stylable with CSS.