4

Overview: I'm making a tempting system for my sites, which at the moment is going quite well and it is working how I would expect it to, the only problems arise when I would like something like {PAGE_SIDEBAR} to show the file template/sidebar.php or something similar.

I am using

//loads of other str_replace here
$body = str_replace("{PAGE_SIDEBAR}, include("template/sidebar.php"), $body);
echo $body;

this works, however it includes the file at the start of body, NOT where {PAGE_SIDEBAR} is. Where the tag is, it shows the number 1.

See screenshots for better explanation:

How the rendered template looks before

Using the insert code above

Also, for point of interest, How it looks using file_get_contents() instead of include(): http:// www.jamesmoorhouse.co.uk/stack_overflow/str_replace/file_get_contents_method.png

Ideally I Am hoping for it to work as it would with the include method, but show up where the file_get_contents method puts it.

2
  • You're missing a quote after {PAGE_SIDEBAR} Commented Jul 4, 2012 at 10:53
  • Ah, typo as I typed it up separately for my post Commented Jul 4, 2012 at 11:22

1 Answer 1

12

You have to capture everything that the include spits out using output buffering to be able to use it as a string:

ob_start();
include("template/sidebar.php");
$str_sidebar = ob_get_clean();
$body = str_replace("{PAGE_SIDEBAR}", $str_sidebar, $body);
echo $body;

If there are lots of placeholders that you want to replace, you might want to use a regular-expression based solution with a callback so that you don't have to repeat this code for each. See my answer here for a primer.

Sign up to request clarification or add additional context in comments.

4 Comments

Good answer! include is a language construct and not a function.
Absolute winner, this is a perfect solution. Thanks!
Just wanted to drop in and say that, three years later, this answer really helped me out. Thanks!
12 Years later and it is still a great answer. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.