douqujin2767 2011-09-13 02:40
浏览 28
已采纳

PHP str_replace问题

Ok, have this code here:

$search = array('{POST}', '{post}');
$replace = $recent['body'];
$message = str_replace($search, $replace, html_entity_decode($params['post_html']));

$params[post_html'] is a variable that holds the users input with either {POST} or {post} defined, for example could be like this, after it gets decoded ofcourse:

<span class="upperframe">
  <span></span>
</span>
<div class="roundframe dp_control_flow">
{POST}
</div>
<span class="lowerframe">
  <span></span>
</span>

Anyways, the problem I'm facing here is, for some reason, str_replace is ALSO replacing and {POST} or {post} strings within the replace parameter: $recent['body'] This should NOT happen, how can I fix this so that it doesn't perform a replace on the thing that needs to be replacing {POST} or {post}?

I did not expect this function to do replaces within the replace variable. OUCH. Is there a way around this? Do I have to use a preg_replace instead? If so, can someone help me with a regex for this?

Thanks guys :)

  • 写回答

1条回答 默认 最新

  • dongxian6285 2011-09-13 02:57
    关注

    use str_ireplace() then you don't need the array for the search and the issue is solved.

    $recent['body']="*test* {post} *test*";
    $params['post_html']="foo {POST} bar";
    
    
    //$search = array('{POST}', '{post}');
    $search = '{post}';
    $replace = $recent['body'];
    $message = str_ireplace($search, $replace, html_entity_decode($params['post_html']));
    
    echo $message; 
    
    
    //with array
    // foo *test* *test* {post} *test* *test* bar
    
    //without
    //foo *test* {post} *test* bar
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输