简体   繁体   English

为什么str_replace()仅替换字符串中一个字符的一个实例?

[英]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. 我有一个较大的字符串变量,该变量是从排序规则为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. 因为它是ASCII格式,所以在将变量放入PDF生成脚本之前,需要替换所有非UTF-8字符。

As we all know, the standards used by PDF are evil. 众所周知,PDF使用的标准是邪恶的。 If I use plain ASCII input it will go insane and cause a rip in space-time. 如果我使用普通的ASCII输入,它将变得疯狂并导致时空撕裂。

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 因此,为了防止对我们的宇宙造成任何损害,我需要帮助弄清楚为什么此str_replace()函数仅替换一种字符类型,而忽略了该字符的任何重复

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. 正如您在第二行的输出中看到的那样, str_replace()不会更改“&”字符。

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() . 好处是,如果您的$tc变量将来会获得更多HTML实体,则您无需摆弄str_replace()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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