doqvzh345334 2012-10-19 06:19
浏览 11
已采纳

PHP str_replace无法按预期工作,返回多个值

I've got this code that uses a str_replace function:

$result = mysql_query("SELECT * FROM table");
$contact_link = "<a href=\"/contact-us/\" class=\"inline\" target=\"_parent\">Contact Us</a>";

while($row = mysql_fetch_array($result))
{
$answer = str_replace(array("contact us","Contact Us","Contact us") , array($contact_link , $contact_link , $contact_link), $row['answer']);
echo $answer;
}

However when I enter the string "contact us" it returns this value:

<a href="/contact-us/" class="inline" target="_parent"><a href="/contact-us/" class="inline" target="_parent">Contact Us</a></a>

And I can't figure out why. I expected it to return Contact Us encapsulated by only one link instead of two. I thought maybe it's because both words start with a lower case letter, so maybe it returns it twice? Once for "contact us" and once for "Contact us"? I've read through the search results on this site and have done some Google searching, but I can't find anything that has the same scenario happening.

In case it's relevant, the reason I'm doing this is so that when my customer updates his website, it will return a link to his contact page. I want to have those three different versions of contact us because the format may change depending on where he uses it.

  • 写回答

2条回答 默认 最新

  • doushu7588 2012-10-19 06:26
    关注

    You could use str_ireplace, which is case insensitive. Have a look at:

    http://php.net/manual/en/function.str-ireplace.php

    the reason you get this output is because of the function first checking for "contact us" and replacing it with the link and then looking for "Contact Us" which is just added, and replacing it again.

    str_ireplace("contact us", $contact_link, $row['answer']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题