无法用字符串替换£和英镑

rob*_*lls 7 php encoding character-encoding str-replace

我有一个包含£符号的HTML字符串,由于某种原因我无法替换它们.我假设这是一个编码问题,虽然我无法弄清楚如何.该网站使用ISO-8859-1进行编码

$str = '<span class="price">£89.99</span>';
var_dump(mb_detect_encoding($str, 'ISO-8859-1', true)); // outputs ISO-8859-1

echo str_replace(array("£","&pound;"),"",$str); // nothing is removed

echo htmlentities($str); // the entire string is converted, including £ to &pound;
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑

本来应该指出我要用£代替&pound; - 我已暂时添加&pound到要替换的项目数组中,以防它已被转换

Iva*_*van 7

只是一个猜测,但即使你的网站输出ISO-8859-1编码,你的实际*.php文件保存为utf-8?我认为str_replace不能正确使用utf-8字符串.要测试它,请尝试:

str_replace(utf8_decode("£"),"&pound;",utf8_decode($str));
Run Code Online (Sandbox Code Playgroud)

是的,如果这样可行,那么你的*.php文件将以utf-8编码保存.这意味着所有字符串常量都在utf-8中.将IDE中的默认编码切换为ISO-8859-1可能是值得的