Home » Php » Replace string from PHP include file

Replace string from PHP include file

Posted by: admin July 12, 2020 Leave a comment

Questions:

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:

<?php

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

?> 

Answer:

You can following function to do that:

$content=includeFileContent('test.php');
echo str_replace('foo', 'cool', $content);

function includeFileContent($fileName)
{
    ob_start();
    ob_implicit_flush(false);
    include($fileName);
    return ob_get_clean();
}

Answer:

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().

<?php
  include 'foo.php';

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

Example of foo.php:

<?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.