PHP:如何将字符串转换为WINDOWS-1252实体/字符?

时间:2014-03-23 21:25:12

标签: php encoding character-encoding html-entities windows-1252

我有以下字符串:

LONDON — Britain’s unemployment rate held steady in the three months through January, reinforcing the Bank of England’s case for keeping interest rates at a record low.

如果我使用类似htmlentities的内容,我会收到以下字符串:

LONDON — Britain’s unemployment rate held steady in the three months through January, reinforcing the Bank of England’s case for keeping interest rates at a record low.

但是我希望获得WINDOWS-1252实体,例如:

LONDON — Britain’s unemployment rate held steady in the three months through January, reinforcing the Bank of England’s case for keeping interest rates at a record low.

我尝试过使用mb_convert_encodingiconvget_html_translation_table等不同功能,但我无法找到办法。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

转换基本上是&#ASCII;格式。因此,使用这些特殊字符的ascii值,您可以在preg_replace_callback函数中轻松实现它。看一下下面的例子:

$text = <<<EOT
LONDON — Britain’s unemployment rate held steady in the three months through January, reinforcing the Bank of England’s case for keeping interest rates at a record low.
EOT;

$text = preg_replace_callback(
    "/([—’])/",   // <-- place characters inside the [] if you need to change
    function ($m){ return "&#".ord($m[1]).";"; },
    $text
);

print "$text\n";

我刚刚在—’内使用了两个([])字符。如果你需要更多,只需逐个添加。