开发者

PHP str_replace issue

开发者 https://www.devze.com 2023-04-04 05:03 出处:网络
Ok, have this code here: $search = array(\'{POST}\', \'{post}\'); $replace = $recent[\'body\']; $message = str_replace($search, $replace, html_entity_decode($params[\'post_html\']));

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} st开发者_开发问答rings 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 :)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号