ob_start "freeze" parameters of functions within

139 Views Asked by At

i'm new to ob_start and i'm in stuck with this function!

i had to parse some tags within text and replace with another text returnet from a function. The problem is that when i call ob_start, functions that follow retains only the first parameters for all sequentials call.. sorry for my explanation, i post the code in a shell:

http://codepad.viper-7.com/SjKqS1

<html>
<body>
    <?php

    $data = <<<EOF

last_name, first_name [test name=12] kardashian, kim mercury, [test name=3] dsdss dsddsdsds sabanana dsdsdsds [test name="abcdefg"] frickenoich EOF;

    $tag = 'test';

    $re = "/\\[". $tag ."[\\]| ]/m";

    preg_match_all( $re, $data, $match );

    $re = "/\[" . $tag . " (.*)\=([\"|\'|[:alnum:]]*)]/m";

    $count = preg_match_all( $re, $data, $match, PREG_SET_ORDER ); 

    for( $i = 0; $i < $count; $i++ ) {

        $count_args = count( $match[ $i ] );

        $args = array();

        // if any argouments, make an argouments array
        if( $count_args ) {
            // make array of argouments
            for($arg_idx = 1; $arg_idx < $count_args; $arg_idx += 2){
                $args[ $match[ $i ][ $arg_idx ] ] = $match[ $i ][ $arg_idx + 1 ];
            }
        }
        echo 'name='.$args['name'];
        echo '<br>';

        ob_start();
        call_user_func( 'test', $args );
         $ret_func = ob_get_clean();
        $data = preg_replace( $re, $ret_func, $data);
    }

    function test( $arg ) {

        echo '<br>test(' . $arg['name'] . ')<br>';
    }

    ?>
</body>

1

There are 1 best solutions below

0
On

At first I thought you needed to include ob_end_clean like:

ob_start();
call_user_func( 'test', $args );
$ret_func = ob_get_clean();
$data = preg_replace( $re, $ret_func, $data);
ob_end_clean();

But then I ran a basic test myself doing this:

<?php
$i = 0;
for($i=0; $i<10; $i++)
{
    ob_start();
    test();
    $ret_func = ob_get_clean();
    echo '<p>' . $ret_func . '</p>';
    ob_end_clean(); //tried with this commented out as well
    echo '<p>' . $ret_func . '</p>';
}
function test()
{
    echo rand(0,100);
}
?>

And it made no difference if I included ob_end_clean or not. So your problem is probably actually how you are rebuilding the args array in each iteration of the loop.