kaleeway kaleeway -4 years ago 53
PHP Question

Why is str_replace() only replacing one instance of a character in a string?

I have a large string variable that is assigned from a database column of type "Text" with Collation latin_swedish_ci.

Because it is in ASCII, I need to replace all non UTF-8 characters before I can put variable into my PDF generation script.

As we all know, the standards used by PDF are evil. If I use plain ASCII input it will go insane and cause a rip in space-time.

So in order to prevent anymore damage to our universe, I need help figuring out why this

function is only replacing one of a character type and ignoring any repeats of this character

Here is my code:

$tc = str_replace (array("\n", "£", "&"), array("<br/>", "&pound;", "&amp;"), $tc);


Terms & Conditions: Mandatory charge of £10 for cancellations.


Terms &amp; Conditions: Mandatory charge of &pound;10 for cancellations.

As you can see in the output on the second line the
does not change the ampersand character.

I wonder if this is because its over two lines or something like that.

So any idea how to get the function to work as I want it to, otherwise well your going to wake up with many Micro Blackholes vanishing your bowl of cereal tomorrow.

Answer Source

It looks like what you are trying to achieve could be done using these 2 functions:


The benefit being that if your $tc variables gets any more HTML entities in the future, you won't have to fiddle with your str_replace().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download