简体   繁体   中英

str_replace is replacing on one line, but not on another

I am running into a strange issue. I have the following code:

$foo = array(
        "some" => array(
            "foo" => "boohoo",
            "bar" => "foobar"
        ),
        "really" => array(
            "foo" => "boohoo",
            "bar" => "barfoo"
        ),
        "strange" => array(
            "foo" => "boohoo",
            "bar" => "foobarfoo"
        ),
        "occurences" => array(
            "foo" => "boohoo",
            "bar" => "barbaz"
        )
    );

$page = "";

foreach($foo as $bar)
{
    $subj = $template->loadTemplate('foobar', true);

    $str = "";

    $str = str_replace("{foo}", $bar['foo'], $subj);
    $str = str_replace("{bar}", $bar['bar'], $subj);

    $page .= $str;
}

The issue here is that when the PHP Code is run, {bar} is replaced in my template but not {foo}. I switched the two str_replace lines around and I got a different result -- {foo} is replaced but {bar} isn't! I've also tried swapping it for preg_replace and nothing changed. For the record, the $template->loadTemplate() function performs no operations on the string loaded, it simply gets the template from a file.

My questions are: why does PHP behave in this fashion, and second, how can I overcome this limitation/bug?

You changing only one, because use same input string for both replaces:

$str = str_replace("{foo}", $bar['foo'], $subj);
$str = str_replace("{bar}", $bar['bar'], $subj);

Try this:

$str = str_replace("{foo}", $bar['foo'], $subj);
$str = str_replace("{bar}", $bar['bar'], $str);

As said CORRUPT you are replacing the strings voiding the previous command.
I'd add that str_replace supports Array() as parameter.

$str = str_replace(Array("{foo}","{bar}"), Array($bar['foo'], $bar['bar']) , $subj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM