为什么 PHP preg_replace {include 'date.php'} 不返回 php 并打印
为什么 PHP preg_replace
{include 'date.php'} 不返回 php?没有eval
如何解决?
header('Content-Type:text/plain');
$str = "Today is {include 'date.php'}.";
echo preg_replace("/\{include '(.*)\'}/e", 'file_get_contents("$1")', $str);
date.php 内容:
<?php echo date('jS \of F'); ?>, 2011
结果: 今天是 ,2011 年。
预期结果:今天是 7 月 13 日。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通过您表达问题的方式,您似乎知道您将文件的内容包含到字符串文字中,因此它没有被评估。
您还知道
eval
不是最好使用的函数,并且想知道如何避免它。那挺好的。您要做的就是在 date.php 中放置一个函数。将函数包含在主文件中,而不是字符串中。在您需要内容时,调用该函数。
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.
除非您使用
eval()
(我不推荐),否则您真的不能指望.php 文件会在调用时执行。include()
的作用是使您所包含的文件中的代码可供脚本使用,它不仅仅是执行它。这就是您的网络服务器调用的引擎所做的事情。如果你想这样做,你必须有“创意”,比如 date.php 的网址上的“nofollow">file_get_contents()
,这将使 Web 服务器执行它并将结果返回给您。实际上,在这种情况下您想要做什么,如果维护 date.php 中的代码确实很重要,请编写一个返回日期字符串的函数,然后在需要时调用它。您甚至可以将其包装在
date.php
中的类中(只是不要将其称为“Date”),然后使用MyDate::myDateFunction()
调用它,其中您可以想要执行它。Unless you use
eval()
(which I do not recommend), you really can't just expect that .php files will get executed on call. Whatinclude()
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 likefile_get_contents()
on the web address ofdate.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 withMyDate::myDateFunction()
where you want to execute it.更改
date.php
以返回值:然后,在主文件中,您可以执行以下操作:
它可以工作,但不是很好。我建议重构您的代码。
Change
date.php
to return the value instead:Then, in your main file, you can do:
It works, but it's not very nice. I would recommend refactoring your code.
如果你想捕获(不仅仅是打印)包含的 PHP 脚本的输出,而你无法改变它,你必须做一个丑陋的解决方法:
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:
这是没有
\e
eval
的解决方案:hello.php
date.php
结果:
Hello!今天是 7 月 21 日。
Here is the solution without
\e
eval
:hello.php
date.php
result:
Hello! Today is 21st of July.