用已经输出数据的函数替换字符串

Replacing string with a function that outputing data already

我正在尝试用已经显示数据的函数替换字符串,或者您已经可以回显数据

    function getData(){
        //echoing data from database, loop
        echo 'printing output';
    }

     function output(){
        return getData();
    }

这是字符串

    $str = "This is some text with php code <?php output();?>";

我这样试过str_replace

str_replace("<?php output();?>", output(), $str);

问题是当我str_replace用函数替换代码时它已经显示数据了。我还尝试了其他功能,例如 preg_replace()preg_replace_callback()

输出函数必须 return 来自 getData 的内容:

function getData(){
    //echoing data from database, loop
    echo 'printing output';
}

 function output(){
    // Start buffer
    ob_start();
    // Call the function and store its contents on buffer
    getData();
    // Get buffer, clean buffer and return contents
    return ob_get_clean();
}
// The string
$str = "This is some text with php code <?php output();?>";
// Replace and output
echo str_replace("<?php output();?>", output(), $str);