开发者

PHP - Error parsing a string with code

I'm having a problem with some code that used to work in PHP 4.X and is not working in PHP 5.2.4

First of all, there is a small example of a code similar to the one is causing the problem. Unfortunately, I haven't been able to reproduce the problem with a small example.

<?php
class Example{

  public function showExample()
  {
    $ind = 1;
    $m   = "method";
    $str2 = "{call method}";

    $str2 = str_replace("{call $m}" , "<?php  print( \$pre$ind ); ?>", $str2);

    echo $str2 . "\n";
   }
}

$e = new Example();
$e -> showExample();
?>

What this code is doing is building a string with some 开发者_如何转开发php code to execute later on. In particular, the code generated will print the value of a variable named "$pre" + a variable number. In this case, the output is the following:

 <?php  print( $pre1 ); ?>

Everything runs fine with this code. The problem is when I use it in the context of a much bigger class, that is part of a framework I've been using for a long time. I cannot paste here the whole source of the class, but the problematic lines are the following (I simplified them a little bit to remove the str_replace, but the error still appears):

        $myVar = "value";
        $myVar2 = 2;
        $str2 = "<?php print( \$myVar$myVar2 );  ?>";

When I load the file, I get the following two messages:

PHP Warning:  Unexpected character in input:  '\' (ASCII=92) state=1 in /Users/giove/Sites/mundial/htmltemplate.php on line 252
PHP Parse error:  syntax error, unexpected T_VARIABLE in /Users/giove/Sites/mundial/htmltemplate.php on line 252

I can fix the warning by removing the '\', but that changes the semantics of the code, so it's not a real possibility.

Now, the weirdest part is I can remove both errors by breaking or removing the sequence "

This seems to be a difference in versions, but I haven't been able to find any mention to it on the change logs.


Now I've got a working solution from Cryo: split the string

 "<?php" 

to prevent its 'evalution' (I'm not sure if that's really an evaluation).

Nevertheless, I still would like to know the reason for this weird behavior.

Cryo: thanks for your help, I'll mark the question as answered in a couple of days.


My guess is that PHP is catching on the re-opening of the php tag <?php, try splitting just that:

$str2 = "<?" . "php print( \$myVar$myVar2 );  ?>";

Or use single quotes and concatenation:

$str2 = '<?php print( $myVar' . $myVar2 . ' );  ?>';


Cryo is on the right track, though I think the actual issue is that PHP evaluates variables within double-quoted strings. However, the slash should prevent the variable from being evaluated. So:

$a = "somestring"
$b = "\$a" // -> \$a
$c = '\$a' // -> \$a

I think your string is getting evaluated in an odd way such that the \ + $myVar is evaluated in a strange way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜