 <p>At first I thought you needed to include <code>ob_end_clean</code> like:</p> <pre><code>ob_start(); call_user_func( 'test', $args ); $ret_func = ob_get_clean(); $data = preg_replace( $re, $ret_func, $data); ob_end_clean(); </code></pre> <p>But then I ran a basic test myself doing this:</p> <pre><code>&lt;?php $i = 0; for($i=0; $i&lt;10; $i++) { ob_start(); test(); $ret_func = ob_get_clean(); echo '&lt;p&gt;' . $ret_func . '&lt;/p&gt;'; ob_end_clean(); //tried with this commented out as well echo '&lt;p&gt;' . $ret_func . '&lt;/p&gt;'; } function test() { echo rand(0,100); } ?&gt; </code></pre> <p>And it made no difference if I included <code>ob_end_clean</code> or not. So your problem is probably actually how you are rebuilding the <code>args</code> array in each iteration of the loop.</p>