Cyclone
Cyclone

Reputation: 15269

str_replace doesn't work with foreach

My code:

$str = array(
        '{$string1}' => 'anything2',
    '{$string2}' => 'something1',
    '{$string3}' => '...'
);

$final = "";
$text = $_POST['content'];
foreach( $str as $key => $val ) {
      $final = str_replace($key, $val, $text);
}

My $text ofc. has {string1} , {string2} and {string3} itself, but it doesn't replace it with the values given in the array.

Why its not working?

Upvotes: 1

Views: 1294

Answers (3)

orafaelreis
orafaelreis

Reputation: 2881

Maybe the different enconding, try this:

$text = utf8_decode($_POST['content']);// or utf8_encode

before loop;

Good lucky!

Upvotes: 1

bilash.saha
bilash.saha

Reputation: 7316

use

 $final = str_replace('{'.$key.'}', $val, $text);

Ref : http://php.net/manual/en/function.str-replace.php

Upvotes: 1

zerkms
zerkms

Reputation: 255005

This code does exactly what you need (without any extra loops):

$final = strtr($_POST['content'], $str);

Upvotes: 1

Related Questions