Reputation: 2531
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?
Upvotes: 2
Views: 3901
Reputation: 449475
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.
Upvotes: 2
Reputation: 11596
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).
Upvotes: 1
Reputation: 57167
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.
Upvotes: 5