简体   繁体   中英

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 str_replace() 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);

Input:

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

Output:

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

As you can see in the output on the second line the str_replace() 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.

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

nl2br(htmlentities($tc));

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() .

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