PHP:str_replace不适用于某些字符

时间:2015-08-06 04:55:07

标签: php str-replace ampersand

我有以下代码来替换某些字符:

<?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 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".

只有第三个工作正常。可能是什么原因 ?我曾经在其他脚本中使用过该代码并且该功能起作用。是什么让一个函数在一个脚本中起作用而在其他脚本中不起作用?使用Firefox作为浏览器。

感谢。

3 个答案:

答案 0 :(得分:1)

如果你这样尝试

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

然后它工作正常。

"&amp;"是unicode字符,如果你想在firebug上查看更改,它会在浏览器上呈现。

答案 1 :(得分:0)

我已经尝试过您的代码,但它运行正常。如果您看到浏览器源代码,则会看到

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".

答案 2 :(得分:0)

抱歉......看起来已被替换!但浏览器会解释转义字符并再次将其显示为“&amp;”。