I have started making a syntax highlighter in php (only a quick one) and so far I have got a code box generator (aka it creates a table with styles that looks good and can display source code and html code). At the moment when writing code with it I do this:
$code = "def example_ruby_code(does_it_work)
" . "(insert tab here) #does_it_work = false
" . "end"
codebox($code, "title_here.rb")
My trouble is that I know that I can't have tabs in html so I used the following:
preg_replace("/\t/", "     ", $code)
(this went in the codebox function)
But it doesn't seem to work, the output just shows no indentation whatsoever. Any ideas? Thanks in advance, ell.
You are missing semi-colon after  :
preg_replace("/\t/", " ", $code);
Note: You may find highlight_string function useful.
Thanks for the semi-colon thing but I'v realised I'v been a complete moron, instead of setting the new value I just called preg_replace! Silly me! Thanks anyway, it still wouldn't of worked without the semi colons. Thanks :)
Related
<?php
$file_handle=fopen("normal.txt","rb");
$i=0;
while (!feof($file_handle)){
$fline=gets($file_handle);
$fparts=preg_split("/:|;\");
$x_values[$i]=(float)$parts[1];
$y_values[$i]=(float)$parts[2];
$i=$i+1;
}
include 'libchart/libchart/classes/libchart.php';
$data_length=sizeof($x_values);
for(i=0;$i< $data_length; $i++)
$dataset -> addPoint(newPoint('',$y_values[$i]));
$chart -> render('figs/text.png');
?>
//this part is not recognised...so it is thhrowing an error.
I think the rest of the code is ok....but that thing keeps throwing that error at the end of my code.I just don't know why...could please someone help me? I'd appreciate that much .That is the only error i find....if there are others too please tell me...i am just a beginner at website designing...
So your help is precious to me
You have delimted your closing quote in this line:
preg_split("/:|;\");
You should put in a second \ to counter it:
preg_split("/:|;\\", $string);
Normally when you put a \ before a quotation, it means "treat the quotation as part of the string". As you don't want it to mean that you need to delimit the delimiter heh. The compiler thinks that the rest of your code is still part of the string - even the syntax highlight here on SO is showing it.
See the difference:
$fline=gets($file_handle);
$fparts=preg_split("/:|;\\", $string);
$x_values[$i]=(float)$parts[1];
$y_values[$i]=(float)$parts[2];
$i=$i+1;
Edit: The elephant in the room was pointed out by KarelG. Good show. preg_split does indeed need to params. Without the extra \ it would have still not worked though :)
I am working on a BB code system for a content manager and I want to be able to use something like [code=php]<?php echo "Hello World!"; ?>[/code] in my textarea. Using GeSHi (A syntax highlighter) I have made the following function to parse the code:
function parsecode($codetype) {
$source = file_get_contents("file.php");
$language = $codetype;
$geshi = new GeSHi($source, $language);
echo '<code class="num">', implode(range(1,count(file("file.php"))), "<br />"), "</code>";
echo $geshi->parse_code();
}
This works perfectly fine!
Now this is where the BB code comes in. Using preg_replace I made a simple system that finds and replaces bits of code:
$find = array(
"/\[code\=(.+?)\](.+?)\[\/code\]/is"
);
$replace = array(
'<?php parsecode("$1"); ?>'
);
Yes, for now this means it only reads the language and parses the file "file.php" but eventually I will have this work different, but that's not important for now.
What happens, is that the BB code gets executed correctly, and the result is that it does in fact execute the code, but it does NOT execute the function parsecode() . I made a small adjustment to find out where the problem is, and made it save to a file and it turns out the file contained the following: <?php parsecode("php"); ?> . Which is exactly what it should contain. When I write this line of code in the file, it executes.
Anything submitted in the textarea gets stored in a file, which is then read using fopen() and then echo'd on a different page.
My question: Why does the function not execute & parse the code like it should?
Thanks ahead!
There is only one way to get PHP code to execute within PHP code (change code dynamically) and that is with eval().
http://www.php.net/manual/en/function.eval.php
This let's you dynamically make code and execute it
Please remember this quote though:
"If eval() is the answer, you're almost certainly asking the wrong question. -- Rasmus Lerdorf, BDFL of PHP"
eval() is known for security vulnerabilities and being exploited. Highly not recommended.
However, as long as you're not using user generated code IN the eval you will be fine. You could put a return around it to get the result only in the database.
You could instead achieve the same effect by running this in the script but not replacing it before it's run in the entry but on the forum page itself...
It keeps killing me for some time...
I'm new to php and I'm writing a parser for price comparison site, therefore I need to have quite a few variables:
$plae = "<pastwisko>";
$user = "<krowa>";
$product "<trawa>";
But without spaces...
Using or echoing those gives me nothing. I've tried to search stackoverflow, google and php documentation and nothing... maybe my english sucks...
Thou I'll be really greatfull for help
If you are echoing those into HTML then they will be parsed as [incorrect] HTML tags by your browser and will not show. You should use htmlentities to make them display as text: http://php.net/manual/en/function.htmlentities.php
You've forgot a "=".
$product "<trawa>";
// Should be.
$product = "<trawa>";
Edit:
Joe has the correct answer to your problem, I ran the script in the terminal and that was the only error I was given. I didn't think of htmlentities, I'm sorry if my post was irrelevant and unnecessary.
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
<?php
$str = '
<?php
//This is a php comment $test and resulted bad!
$text_cool++;
?>
';
$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('<','>','/'),$result);
$resultArray = explode("\n",$result);
foreach ($resultArray as $i) {
echo $i.'</br>';
}
?>
Problem Demo Screen
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.)
Can anyone help me solve this problem?
I'm Aware of highlight_string() function!
THANKS IN ADVANCE!
Reinventing the wheel?
highlight_string()
Also, this is why they have parsers, and regex (despite popular demand) should not be used as a parser.
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);
with
//regular expression.:
//#([^(%%%%|\"|')]*)([\$](?!\()(.*?)(?=(\W)))#
//replacement text:
//$1<span style=\"color:green;\">$2</span>
$result = preg_replace("#([^(%%%%|\"|')]*)([\$](?!\()(.*?)(?=(\W)))#","$1<span style=\"color:green;\">$2</span>",$result);
Personally, I think your best bet is to use CSS selectors. Replace style=\"color:gray;\" with class="comment-text" and style=\"color:green;\" with class="variable-text" and this CSS should work for you:
.variable-text {
color: #00E;
}
.comment-text .comment-text.variable-text {
color: #DDD;
}
Insert don't use regex to parse irregular languages here
anyway, it looks like you've run into a prime example of why regular expressions are not suited for this kind of problem. You'd be better off looking into PHP's highlight_string functionality
Well, you don't seem to care that php already has a function like this.
But because of the structure of php code one cannot simply use a regex for this or walk into mordor (the latter being the easier).
You have to use a parser or you will fly over the cuckoo's nest soon.
I am trying to implement this code into Wordpress:
<?php
$basename = substr(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4);
?>
No matter in which of the Wordpress php files I put this in, it corrupts it. Saying that it cannot find the page. This is very bizarre. Do anyone know why it is behaving like this? Or any direct solutions to how I can add this code to Wordpress?
Note that I am not experienced with PHP so any respond with detail would be appreciated.
This is a parse error.
You need a closing bracket at the end:
$basename = substr(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4)
It's a good thing to use a text editor or IDE with syntax highlighting that can reveal such things, they are often difficult to see with the naked eye.
That said, as #JMC Creative points out, this looks very kludgy, and there is bound to be a better way to achieve what you want. What is the goal of this?
You're over-complicating what you're trying to do.
$fileName = strtolower(basename(__FILE__, ".php"));
You may want to use php_self instead of file, it depends on what you're after.
The answer is:
$basename = strtolower( substr(basename($_SERVER['PHP_SELF']),0,-4));