【问题标题】:str_replace doesn't work with foreachstr_replace 不适用于 foreach
【发布时间】:2011-10-25 02:23:49
【问题描述】:

我的代码:

$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} 本身,但它不会用数组中给定的值替换它。

为什么它不起作用?

【问题讨论】:

  • $final 返回什么?
  • 您的意思是分配而不是附加到最终结果吗?你有一个 =,但也许你想要 .=.
  • @mqsoh 我只需要将$_POST['content'] 内容替换为数组中的值,我不需要附加任何内容。

标签: php foreach str-replace


【解决方案1】:

这段代码完全符合您的需要(没有任何额外的循环):

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

【讨论】:

    【解决方案2】:

    使用

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

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

    【讨论】:

      【解决方案3】:

      也许是不同的编码,试试这个:

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

      循环前;

      祝你好运!

      【讨论】:

        猜你喜欢
        • 2013-01-22
        • 1970-01-01
        • 2011-07-10
        • 1970-01-01
        • 2013-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-19
        相关资源
        最近更新 更多