简体   繁体   English

PHP:str_replace不适用于某些字符

[英]PHP: str_replace does not work for certain characters

I have the following code to replace certain characters: 我有以下代码替换某些字符:

<?php
function xmlEscape($string)
{
    return str_replace(array('&', '<', '>', '\'', '"'), array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;'), $string);
}
$xxx = 'The character & is ampersand and < stands for "less than". ';

echo xmlEscape($xxx)." <p/>";
echo str_replace ('&', '&amp;', $xxx."<p/>");
echo str_replace ( 'character','letter', $xxx);
?>

The result is : 结果是:

The character & is ampersand and < stands for "less than".
The character & is ampersand and < stands for "less than".
The letter & is ampersand and < stands for "less than".

Only the third works fine. 只有第三个可以正常工作。 What could be the cause ? 可能是什么原因 ? I once used that code in other scripts and that function worked. 我曾经在其他脚本中使用过该代码,并且该功能有效。 What makes a function works in one script and does not work in others ? 是什么让功能在一个脚本中起作用而在其他脚本中不起作用? Using Firefox as browser. 使用Firefox作为浏览器。

Thanks. 谢谢。

if you trying like this 如果你这样尝试

echo str_replace ('&', 'amp', $xxx."<p/>");

then it is working fine. 那就很好了。

"&amp;" is unicode character and it is rendering on browser if you want to see the changes check it on firebug. 是unicode字符,如果要查看更改,请在浏览器上呈现,请在firebug上进行检查。

I've tried your code and it works properly. 我已经尝试过您的代码,并且可以正常工作。 If you see your browser source code, you will see 如果您看到浏览器源代码,则将看到

The character &amp; is ampersand and &lt; stands for "less than".  <p>
The character &amp; is ampersand and &lt; stands for "less than". </p>
<p>The letter &amp; is ampersand and &lt; stands for "less than".

Sorry... Looks like it is replaced! 抱歉...看起来好像被替换了! But the browser interprets the escape character and displays it again as "&". 但是浏览器会解释转义符,并将其再次显示为“&”。

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

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