使用 str_replace 并包含在一起 (php)
我的网页中有一个页脚,该页脚称为 footer.php。我希望页脚根据其他变量具有不同的图像。我想做这样的事情:
if (x=1) {include (str_replace('logo1.jpg','logo2.jpg','footer.php'));}
else
{include 'footer.php';}
但这不起作用,它只是进行常规包含。有没有办法在包含文件的同时替换文件中的文本?
I have a footer in a web page, the footer is called footer.php. I'd like the footer to have a different image depending on other variables. I want to do something like this:
if (x=1) {include (str_replace('logo1.jpg','logo2.jpg','footer.php'));}
else
{include 'footer.php';}
But this doesn't work, it just does a regular include. Is there a way to replace text in files while including them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用类似以下内容:
////footer.php
基本上,您将尝试对字符串“footer.php”进行替换,而不是对文件本身进行替换。这里适当的方法是为图像使用一个变量,并让页脚在提供图像时使用该变量。
Use something like:
////footer.php
Basically, what you had would try to do the replace on the string 'footer.php', not the file itself. The appropriate approach here would be to use a variable for your image and have the footer use that variable when supplying the image.
是的,但是您包含的文件必须返回其内容。
footer.php
那么你可以这样做,
这没有任何问题,但感觉有点奇怪。
如果我是你,我会让 include() 只是像 Jonathan Fingland 提议的那样使用预设变量,或者像 Tomas Markauskas 提议的那样获取页脚文件的内容。
Yes there is, but your included file would have to return its contents.
footer.php
then you can do
there's nothing wrong with this but it feels slightly weird, though.
If I were you, I would have the include() just work with a pre-set variable as Jonathan Fingland proposes, or fetch the contents of a footer file like Tomas Markauskas proposes.
您的示例不起作用,因为您要将字符串“footer.php”中的“logo1.jpg”替换为“logo2.jpg”。替换的结果仍然是“footer.php”,然后您只需包含一个名称与您的字符串匹配的文件。
如果你确实需要替换 php 文件中的字符串并随后执行它,你可以这样做:
但是有更好的方法来实现你想要的(例如,请参阅 Jonathan Fingland 的答案)。
Your example isn't working because you're replacing 'logo1.jpg' with 'logo2.jpg' in the string 'footer.php'. The result of the replacement is still 'footer.php' and then you're just including a file with the name that matches your string.
If you really need to replace a string in a php file and execute it afterwards, you could do something like this:
But there are better ways to achieve what you want (see answer from Jonathan Fingland for an example).