PHP str_replace 问题

发布于 2024-12-04 06:38:33 字数 852 浏览 0 评论 0原文

好的,这里有这段代码:

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

$params[post_html'] 是一个变量,用于保存定义了 {POST} 或 {post} 的用户输入,例如在解码后可能像这样当然:

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

无论如何,我在这里面临的问题是,由于某种原因, str_replace 也替换了 {POST}{post}替换参数中的字符串: $recent['body'] 这种情况不应该发生,我该如何解决这个问题,以便它不会对需要替换的内容执行替换{POST}{post}

我没想到这个函数会在替换变量中进行替换。哎哟。有办法解决这个问题吗?我必须使用 preg_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 :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陪你到最终 2024-12-11 06:38:33

使用 str_ireplace() 那么您不需要数组进行搜索,问题就解决了。

$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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文