View Full Version : Replacing text in PHP
chainprayer
Mar 31, 2009, 01:33 AM
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
angelwatt
Mar 31, 2009, 08:21 AM
You would need to do it inside include.php.
SrWebDeveloper
Mar 31, 2009, 08:21 AM
There are numerous ways, here is one of my favorites...
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
vBulletin® v3.8.6, Copyright ©2000-2012, Jelsoft Enterprises Ltd.