SoLoGHoST
SoLoGHoST

Reputation: 2689

PHP str_replace issue

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 :)

Upvotes: 1

Views: 180

Answers (1)

user557846
user557846

Reputation:

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

Upvotes: 1

Related Questions