[英]str_replace doesn't work with foreach
我的代碼:
$str = array(
'{$string1}' => 'anything2',
'{$string2}' => 'something1',
'{$string3}' => '...'
);
$final = "";
$text = $_POST['content'];
foreach( $str as $key => $val ) {
$final = str_replace($key, $val, $text);
}
我的$text
ofc。 具有{string1}
, {string2}
和{string3}
本身,但不會將其替換為數組中給出的值。
為什么不工作?
也許是不同的想法,試試這個:
$ text = utf8_decode($ _ POST ['content']); //或utf8_encode
在循環之前;
好幸運!
這段代碼完全滿足您的需求(沒有任何額外的循環):
$final = strtr($_POST['content'], $str);
采用
$final = str_replace('{'.$key.'}', $val, $text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.