php 如何在php中将重音字符转换为html?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17624909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:11:22  来源:igfitidea点击:

How to convert accented chars to html in php?

phphtml

提问by Gabriel

I have foreign language strings stored in utf8. When displaying them, I want them to be transform in such a way that accented chars become their html counterparts, e.g. ébecomes é

我有存储在 utf8 中的外语字符串。在显示它们时,我希望它们以这样的方式进行转换,即重音字符变成它们的 html 对应物,例如é变成é

However I phrase my search, all I can find is htmlentities()which does not do it.

然而,我用我的搜索措辞,我能找到的只是htmlentities()不这样做。

回答by Peter F

I found this is a very simple solution to this problem.

我发现这是这个问题的一个非常简单的解决方案。

The first part tries to encode the text. If the $output returns a blank string, then the value is utf8 encoded and then the html entities are created.

第一部分尝试对文本进行编码。如果 $output 返回一个空字符串,则该值是 utf8 编码的,然后创建 html 实体。

$output = htmlentities($value, 0, "UTF-8");
if ($output == "") {
    $output = htmlentities(utf8_encode($value), 0, "UTF-8");
}

Example:

例子:

Montréal

Output:

输出:

Montréal

回答by jcsanyi

Make sure you're properly specifying the encoding when you call htmlentities().

确保在调用时正确指定了编码htmlentities()

The documentation shows that it defaults to 'UTF-8', but if you read down a bit further, you'll see that that's new as of PHP 5.4. If you're using an older version, the default is actually 'ISO-8859-1', and you'll need to make sure you explicitly specify it as 'UTF-8'instead of relying on the default behaviour.

文档显示它默认为'UTF-8',但如果您进一步阅读,您会发现这是 PHP 5.4 的新内容。如果您使用的是旧版本,则默认值实际上是'ISO-8859-1',并且您需要确保将其明确指定为 as'UTF-8'而不是依赖于默认行为。

htmlentities($string, 0, 'UTF-8');