• 0

[php] str_replace problem


Question

Hi,

I have a site and I need to change the way it functions basically $pageBody contains all the code for the page, but where I have a form I want to be able to include it using ==Contact== which will then load a contact form in the place of the text. The form will be loaded in a form called Contact.txt. However I need this to be done dynamically as there will undoubtedly be other bits that I try to include in that way.

Here is what I have done so far;

$pageBody = str_replace("==(.*?)==", include($1.".txt"), $pageBody);

But that gives me the following error;

Parse error: syntax error, unexpected T_DNUMBER, expecting T_VARIABLE or '$' in /home/betajto/public_html/CMS/index.php on line 16

Any help would be great!

Thanks

Joe

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

include() is not the right function when you only want to retrieve the contents of a file, you should use file_get_contents() for that. include() reads a file and parses it as PHP in the current scope, whereas file_get_contents() simply reads a file as a regular string.

Also, calling the function like that won't work. The result of file_get_contents() needs to be passed to preg_replace() as an argument so it must be evaluated before preg_replace(), which is not possible like this. However, there are a few ways to do some custom handling of the replacement.

  • Use the "e" modifier in the pattern.
    The "e" modifier tells PHP to parse the replacement string as PHP code rather than just reading it as a plain string. In your case, this could look something like:
    <?php
    $pageBody = preg_replace("#==(.*?)==#e", "file_get_contents('\\1.txt')", $pageBody);
    ?>


    Note the quotes around file_get_contents: we're just passing a string containing the code which preg_replace will then evaluate.

  • Use preg_replace_callback.
    If you need some more flexibility for the replacement, you might not be able to squeeze all your logic inside a string passed with the "e" modifier. In such cases, it is better to use a separate function which does the handling and use the name of that function in preg_replace_callback.
    <?php
    function my_custom_replace_callback($matches) {
       // You can even do some checks here to see whether the file actually exists
       // or implement some kind of protection by using a white list of allowed files.
       // You just need to make sure that you return something (or an empty string).
       $file = $matches[1] . '.txt';
       return file_get_contents($file);
    }
    // ...
    $pageBody = preg_replace_callback("#==(.*?)==#", "my_custom_replace_callback", $pageBody);
    ?>


Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.