PHP Regex problem! - php

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.

Related

Can I "fix" misplaced HTML tags using PHP?

Is there a quick and easy way to fix HTML tags that are misplaced, in a web document? Such as:
<strong><span style="border:1px;">Text</strong></span>
/\ /\
|______________________________________|
So that it looks like:
<strong><span style="border:1px;">Text</span></strong>
Edit: you are suggesting HTML fixers, but what I'm looking for is a function type solution. Would it help if you could consider this to be BBcode? [b][u]Text[\b][\u]
I think the best solution is using Html Purifier, works pretty good:
Demo: http://htmlpurifier.org/demo.php
Works with your input perfectly.
How should a computer know whether you meant for the span to be inside the strong, or the other way around?
The "quick and easy way" is to run your document through an HTML validator, then fix the issues that it identifies using your noggin and keyboard.
You can use tidy::repairFile() or tidy::repairString(), but repairing is not straightforward, so you can never be sure the result will be what you expect. Example from the documentation:
<?php
$file = 'file.html';
$tidy = new tidy();
$repaired = $tidy->repairfile($file);
rename($file, $file . '.bak');
file_put_contents($file, $repaired);
?>

Angle brackets in PHP string

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.

get contents in a span id using regex help

I want to get the value inside a span id or div id. For example from
<span id="lastPrice">29.00</span>
i want to get the 29.00. please help.
If you want to do this through regexp that badly.
$string = "<span id=\"lastPrice\">29.00</span>";
preg_match("/\<span id\=\"lastPrice\"\>([\d.]+?)\<\/span\>/",$string,$match);
print "<pre>"; var_dump($match[1]); print "</pre>";
But there are far more better ways.
Take a look at XPath => PHP - Searching and filtering with XPath
[...] XPath is a darn sight easier than regular expressions for basic usage. That said, it might take a little while to get your head around all the possibilities it opens up to you!
Google will give u plenty of examples and tutorials.

PHP - Preg_match_all - Regular Expression - help

i've been working on this question since yesterday, i have the following code..
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
echo "evalia:".$param[1]."<br>";
$i=0;
while($i<100)
$i++;
?>
cvbcbcbcvb
<?php
echo "asdsad";
for($i=0;$i<100;$i++)
{
echo $i;
}
?>
and i need to get what is inside the tag.... can anyone help me?
ok i explained myself really badly....
in another page i use file_get_contents to get this code ( this is only a test page nothing more) ... i can't use include for a serious reason so i need to use eval on the code inside the php tag so what i really need is the regular expression to grab everything inside the tag..
Im my opinion you don't need to extarct the code from php tags. You can just eval all the content of the file:
eval(" ?>$file_content<?php ");
You can still use include which is actually quite like eval:
include('data:text/plain;base64,'.base64_encode($file_content));
See data://Docs for details about the data: (ยป RFC 2397) stream wrapper.
See as well Karolis answer.
preg_match("|<\?php(.*?)\?>|msU", $string, $match);
eval($match[1]);
is it your answer?

A simple line of PHP corrupts Wordpress

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));

Categories