I was creating a Syntax Highlighter in PHP but I was failed! You see when I was creating script comments (//) Syntax Highlighting (gray) , I was facing some problems. So I just created a shortened version of my Syntax Highlighting Function to show you all my problem. See whenever a PHP variable ,i.e., $example, is inserted in between the comment it doesn't get grayed as it should be according to my Syntax Highlighter. You see I'm using preg_replace() to achieve this. But the regex of it which I'm using currently doesn't seem to be right. I tried out almost everything that I know about it, but it doesn't work. See the demo code below.

Problem Demo Code

  $str = '
    //This is a php comment $test and resulted bad!
  $result = str_replace(array('<','>','/'),array('[',']','%%'),$str);
  $result = preg_replace("/%%%%(.*?)(?=(\n))/","<span style=\"color:gray;\">$0</span>",$result);
  $result = preg_replace("/(?<!\"|'|%%%%\w\s\t)[\$](?!\()(.*?)(?=(\W))/","<span style=\"color:green;\">$0</span>",$result);
  $result = str_replace(array('[',']','%%'),array('&lt;','&gt;','/'),$result);
  $resultArray = explode("\n",$result);
  foreach ($resultArray as $i) {
    echo $i.'</br>';

Problem Demo Screen

enter image description here

So you see the result I want is that $test in the comment string of the 'Demo Screen' above should also be colored as gray!(See below.)

enter image description here

Can anyone help me solve this problem?

I'm Aware of highlight_string() function!



As PHP has this facility built in, there is a question of why you are doing it, not that it helps to say that.

Written by Orbling

You're really rolling your own? Why reinvent the wheel?

Written by Matt Ball

Please buddy help me out.

Written by Jack Billy

Accepted Answer

I agree, that you should use existing, parsers. Every ide has a php parser, and many people have written more of them.

That said, I do think it is worth the mental exercise. So, you can replace:

$result = preg_replace("/(?<!\"|')[\$](?!\()(.*?)(?=(\W))/","<span style=\"color:green;\">$0</span>",$result);


//regular expression.:

//replacement text:
//$1<span style=\"color:green;\">$2</span>

$result = preg_replace("#([^(%%%%|\"|')]*)([\$](?!\()(.*?)(?=(\W)))#","$1<span style=\"color:green;\">$2</span>",$result);
Written by Jacob Eggers
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki