简体   繁体   中英

PHP str_replace not working as expected, returning multiple values

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.

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']);

The real problem is your contact links inner text is also getting replaced with the contact link itself!

So, when you are replacing the first instance of contact us, you were adding another. Instead you could replace all in one go as Pedryk suggests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM