Home » Php » Replace string from PHP include file

Replace string from PHP include file

Posted by: admin July 12, 2020 Leave a comment


Let’s say I have an include file, foo.php, and it contains the text “this file is foo”.

So, when I load the include using <?php include 'foo.php'; ?>, I want to be able to replace a string from the include before displaying the text it contains.

So let’s say I want to replace “foo” from the include with “cool”.

Make sense?

How to&Answers:

You can use this:


function callback($buffer)
  return (str_replace("foo", "cool", $buffer));
include 'foo.php';



You can following function to do that:

echo str_replace('foo', 'cool', $content);

function includeFileContent($fileName)
    return ob_get_clean();


The basic idea is good, the implementation practice used is not.
Include is used to load a file in memory as a whole. You should only use ‘include …’ when you do not want to change anything on the included file. With an include you load a file into memory and intend to use it for processing anything that comes next.

A classic example for including on the fly is a template file.
A classic example for include_once is a file with basic functions.

BTW, I prefer require_once above include_once.

If you want to change the content of a file before showing it, you should load the content of the file in another function and replace its content before showing it. The function that performs the change of the content should be in a file that you included(_once).
The file of which the content should be replaced should be loaded using some type of filehandler. Because you want to replace text I would recommend using file_get_contents().

  include 'foo.php';

  $output = file_get_contents('bar.php');
  $output = processContent($output);

Example of foo.php:

  function processContent($pText){
    return str_replace('foo','cool',$pText);

Using this technique helps you to separate semantics from actual output and can be a good technique to return personalized messages at runtime.