Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chainprayer

macrumors 6502a
Original poster
Feb 10, 2008
638
2
Hello!

I am looking for a way to include a file in PHP, but replace some of the text of the include with different text.

For example, if include.php contains the text "I like apples. Yum!", I want to be able to replace any mention of the string "apples" with "oranges" before it is included in the page.

Is there a simple way to do this?

Thank you! :D
 
There are numerous ways, here is one of my favorites...

PHP:
ob_start();
include_once "filename.php";
$buffer=ob_get_contents();
ob_end_clean();

$buffer=str_replace("this","with that",$buffer); // or whatever method you prefer to search/replace
print $buffer;

Other methods include reading in the php as a file, using system commands to execute greps and awk/sed before the include, etc. But I prefer the rather simple method of using PHP's very powerful output buffering functions. My code opens an output buffer, I include the file as normal, store the output in a variable called $buffer, clean the output buffer, do my search/replace and output $buffer.

Note: If you need to search/replace the actual HTML source (not the output of source generated by server side processing) then read in the file into memory just like its a text file and then parse. Most people only want to parse the output so I listed that method first plus the way you phrased your requirements the output buffering method should work just fine for you. But if you need an example of reading in a file, lemme know.

-jim
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.