开发者

Using str_replace and include together (php)

I have a footer in a web page, the foo开发者_如何学Cter 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?


Use something like:

if (x==1) {
    $image='logo1.jpg';
} else {
    $image = 'logo2.jpg';
}

include('footer.php');

////footer.php

echo "<img src='".$image."'/>";

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.


Is there a way to replace text in files while including them?

Yes there is, but your included file would have to return its contents.

footer.php

<?
return "<img src='#image'>";
?>

then you can do

echo str_replace("#image", "image.jpg", include("footer.php"));

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.


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:

$file = file_get_contents('footer.php');
$file = str_replace('logo1.jpg', 'logo2.jpg', $file);
eval($file);

But there are better ways to achieve what you want (see answer from Jonathan Fingland for an example).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜