Replacing text in PHP

Discussion in 'Web Design and Development' started by chainprayer, Mar 30, 2009.

  1. chainprayer macrumors 6502a

    Feb 10, 2008

    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
  2. angelwatt Moderator emeritus


    Aug 16, 2005
  3. SrWebDeveloper macrumors 68000


    Dec 7, 2007
    Alexandria, VA, USA
    There are numerous ways, here is one of my favorites...


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


Share This Page