我有2个URL,我想用'&amp'替换'&',用'%23'替换'#',所以尽管我会使用:
list($upUrl, $downUrl) = str_replace(["&", "#"], ["&", "%23"], [$upUrl, $downUrl]);
但是不会出现'&amp'的替换-'&'保持不变。使用str_replace不影响正常工作:
$upUrl = str_replace("&", "&", $upUrl);
如果我将'&amp'更改为另一个字符串,则可以正常进行。这是演示此问题的代码段:
<?php
define("NL", "\n<br>");
$upUrl = "upUrl ampersand=& hash=#";
$downUrl = "downUrl ampersand=& hash=#";
echo $upUrl.NL;
echo $downUrl.NL.NL;
list($upUrl, $downUrl) = str_replace(["&", "#"], ["&", "%23"], [$upUrl, $downUrl]);
echo $upUrl.NL;
echo $downUrl.NL.NL;
$upUrl = str_replace("&", "&", $upUrl);
echo $upUrl.NL;
echo $downUrl.NL;
?>
用'\'转义'&'没什么区别。
问题:我是在做错什么还是这只是PHP的古怪?
在浏览器中运行此代码使其外观没有进行替换,但实际上是替换,只是&
(甚至是您的“有问题的” &
)在其中显示为&
浏览器。您的代码按预期工作:
upUrl ampersand=& hash=#
<br>downUrl ampersand=& hash=#
<br>
<br>upUrl ampersand=& hash=%23
<br>downUrl ampersand=& hash=%23
<br>
<br>upUrl ampersand=&amp hash=%23
<br>downUrl ampersand=& hash=%23
<br>