Replace line from include PHP file

Say I have an include file, foo.php, and it contains the text "this file is foo".

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

So, let's say I want to replace "foo" with include "cool".

Make sense?

+4
source share
3 answers

You can use this:

 <?php function callback($buffer) { return (str_replace("foo", "cool", $buffer)); } ob_start("callback"); include 'foo.php'; ob_end_flush(); ?> 
+7
source

You can execute the following function:

 $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(); } 
+2
source

The basic idea is good, implementation practice is not. Include is used to load a file into memory in general. You should use "include ..." when you do not want to change anything in the included file. With inclusion, you load the file into memory and intend to use it to process everything that comes next.

A classic example of enabling on the fly is a template file. A classic example of include_once is a file with basic functions.

By the way, I prefer require_once over include_once.

If you want to change the contents of a file before displaying it, you must load the contents of the file into another function and replace its contents before showing it. The function that performs the content change must be in the file you included (_once). The file from which the content is to be replaced must be loaded using some type of file handler. Since you want to replace the text, I would recommend using file_get_contents ().

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

Example foo.php:

 <?php function processContent($pText){ return str_replace('foo','cool',$pText); } ?> 

Using this technique helps separate semantics from actual output and can be a good technique for returning personalized messages at runtime.

0
source

Source: https://habr.com/ru/post/1499370/


All Articles