Search code examples
phpincludepreg-replace-callback

How to include a file within preg_replace_callback


lets say example.php is

echo("123");

How can i change regex matched include rule within this string "abc{include 'example.php'}def" with php executed included result. Result should be "abc123def"

I wrote this code and works but its not running php code within the included file. So results is "abcecho("123);def", which is not i'm looking for.

preg_replace_callback("/\{\s*include\s*'(.*?)\'\s*}/", function($m) { return file_get_contents($m[1]);}, $str);

Thanks


Solution

  • You can use functions of output buffering. Then callback function would be:

    function($m) {
       ob_start();
       include($m[1]);
       $out = ob_get_contents();
       ob_end_clean();
       return $out;
    }