|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76571 str_replace fails to replace string in special output buffered environment
Submitted: 2018-07-03 07:22 UTC Modified: 2018-07-03 09:12 UTC
From: roland at nextendweb dot com Assigned:
Status: Not a bug Package: Output Control
PHP Version: 7.2.7 OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
Solve the problem:
35 - 35 = ?
Subscribe to this entry?

 [2018-07-03 07:22 UTC] roland at nextendweb dot com

Test script:
class a {

    private static $bug = 'World';

    public static function parse_output($buffer) {

        $buffer = str_replace('there', self::$bug, $buffer);

        self::$bug = 'What?';

        return $buffer;

echo "Hello there";

$content = ob_get_contents();

echo $content;

Expected result:
Hello World

Actual result:
Hello What?


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2018-07-03 08:41 UTC]
-Status: Open +Status: Not a bug
 [2018-07-03 08:41 UTC]
> The [output_callback] function will be called when the output buffer is flushed (sent) or cleaned (with
> ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the
> request.

1. When you echo "Hello there", the callback is *not invoked immediately*
2. ob_get_contents returns "Hello there" back
3. ob_clean sends "Hello there" to the callback, which replaces using "World", but the result is discarded
4. You echo the original "Hello there" again
5. ob_end_flush sends the new "Hello there" to the callback, which replaces using "What?", and the result is sent

Is there a reasonable use case behind this problem? Because otherwise what you should be doing is simply
  echo "Hello there";
 [2018-07-03 09:05 UTC] roland at nextendweb dot com
Well, it makes sense. So I should use the output callback phase parameter to check.
Could you tell me which is the phase which runs only once when the output buffer closed completely?

class a {

    private static $bug = 'World';

    public static function parse_output($buffer, $phase) {

        if ( $phase & PHP_OUTPUT_HANDLER_FINAL ){

            $buffer = str_replace('there', self::$bug, $buffer);
            self::$bug = 'What?';

        return $buffer;
 [2018-07-03 09:12 UTC]
FINAL is the one.
PHP Copyright © 2001-2023 The PHP Group
All rights reserved.
Last updated: Thu Dec 07 14:01:28 2023 UTC