I need some help figuring out the most optimal way to search and replace occurences of a string within an included file without actualy rewriting the file. The purpose is to do this without needing any php code in the included files. Here is the specific logic behind my case:

if (isset($iframes))

search all occurences of "[target]"

and replace with "target='someframe'"

include "file.html";
} else {

search all occurences of "[target]"

and replace with ""

include "file.html";
}

I suppose the logic is the same as what is used with BBcode but I cant figure out if it's best to read the file into an array, make the search and replace and output the results or if there is a better way.
Anyone?

Thanks

    Are you looking to take "file.html" and replace a token in file.html with real data?

    If so, using include() will not help you out. You'll need to read in the file (fopen() is one option) and then parse data - either in array form or as one string. I might recommend parsing it as one string. As one string, the regular expression functions can then do a global search/replace on that one string instead of running for each array element.

      Thanks, regarding include, that was part of my question actually. So if I read the file, perform the s&r in one string, all I need to do is to print that string afterwards?

        Ok I couldnt figure out the fopen method but came up with this:

        print (ereg_replace( $searched, $replacement, (implode("",file("file.html"))) ));

        This does exactly what I want, except that it's so painfully slow!
        What is the alternative?

          You've got the right concept.

          Are you looping that statement or just running it once? If you're looping it, then I'd pull the file() out because you don't need to open the file each time.

          You might also try preg_replace() instead of ereg_replace() - unless you have a reason for using ereg_replace(). PHP.net says preg_replace() is a lot quicker than ereg_replace() and that might help you out.

            I'm not looping the whole thing as it is simply a s&r function for the entire page. Well actually, I run it twice for two different search and replace processes. Maybe I can reduce the time a bit but making my two searches into one array? I'll try...
            As for preg_replace, my search include a ">" tag so I have to use ereg to make it work. Unless I missed something that is.

              Write a Reply...