开发者

Why PHP preg_replace {include 'date.php'} does not return php and prints <?php echo date('jS \of F'); ?>

Why PHP preg_replace {include 'date.php'} does开发者_如何学C not return php? How to solve it without eval?

header('Content-Type:text/plain');

$str = "Today is {include 'date.php'}.";

echo preg_replace("/\{include '(.*)\'}/e", 'file_get_contents("$1")', $str);

date.php content:

<?php echo date('jS \of F'); ?>, 2011

Result: Today is <?php echo date('jS \of F'); ?>, 2011.

Expected result: Today is 13th of July.


By the way you phrased your question you seem to know that you included the contents of the file into a string literal, so it did not get evaluated.

You also know eval is not the best function to use, and want to know how to avoid it. That's good.

The thing you want to do is to put a function in date.php. Include the function, not in a string, in your main file. At the point you want the content, call the function.


Unless you use eval() (which I do not recommend), you really can't just expect that .php files will get executed on call. What include() does is make the code in the file you included available to your script, it doesn't just execute it. That's what the engine your web server calls does. If you wanted to do that, you'd have to be "creative" with something like file_get_contents() on the web address of date.php, which would make the web server execute it and return the result to you.

Really, what you want to do in this case, if it's really that important to maintain distinction for the code in date.php, write a function that returns the date string and then call it whenever you want to. You can even wrap it in a class in date.php (just don't call it "Date") and then call it with MyDate::myDateFunction() where you want to execute it.


Change date.php to return the value instead:

<?php return date('jS \of F') . ', 2011';

Then, in your main file, you can do:

$date = include 'date.php';
echo 'Today is ' . $date;

It works, but it's not very nice. I would recommend refactoring your code.


If you want to capture (not only print) the ouptput of an included PHP script which you cannot alter, you have to do an ugly workaround:

<?php

ob_start();
include 'date.php';
$date = ob_get_contents();
ob_end_clean();

$str = "Today is {$date}.";

?>


Here is the solution without \e eval:

$str = "{include 'hello.php'}Today is {include 'date.php'}.";

echo preg_replace_callback("/\{include '(.*?)\'}/", function($m) {
  return include($m[1]);
}, $str);

hello.php

<?php return "Hello!\n"; ?>

date.php

<?php return date('jS \of F'); ?>, 2011

result: Hello! Today is 21st of July.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜