简体   繁体   English

在PHP中更改文本编码的最佳方法是什么

[英]What is the best way to change the encoding of text in PHP

I want to run text through a filter to ensure it is all UTF-8 encoded. 我想通过过滤器运行文本,以确保所有文本都是UTF-8编码的。 What is the recommended way to do this with PHP? 使用PHP进行此操作的推荐方法是什么?

Your question is unclear, are you trying to encode something? 您的问题不清楚,您是否要编码? If so utf8_encode is your friend. 如果是这样, utf8_encode是您的朋友。 Are you trying to determine if it doesn't need to be encoded? 您是否要确定是否不需要编码? If so, utf8_encode is still your friend, because you can check that the result is the same as the input! 如果是这样, utf8_encode仍然是您的朋友,因为您可以检查结果是否与输入的相同!

此处检查多字节字符串功能

You need to know in what character set your input string is encoded, or this will go nowhere fast. 您需要知道您输入的字符串是用什么字符集编码的,否则将无法快速进行。

If you want to do it correctly, this article may be helpful: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) 如果您想正确执行此操作,那么这篇文章可能会对您有所帮助: 每个软件开发人员绝对,肯定地必须绝对了解Unicode和字符集(无借口!)

Given a stream of bytes, you have to know what encoding it is to begin with - email use mime headers to specify the encoding, http uses http headers to specify the encoding. 给定字节流,您必须知道开始使用哪种编码-电子邮件使用mime标头指定编码,http使用http标头指定编码。 Also, you can specify the encoding in a meta tag in a web page, but it is not always honored. 另外,您可以在网页的meta标记中指定编码,但是并不总是遵循这种编码。

Anyway, once you know what encoding you want to convert from, use iconv to convert it to utf8. 无论如何,一旦知道要转换的编码,请使用iconv将其转换为utf8。 look at the iconv section of the php docs, there's lots of good info there. 看一下php文档的iconv部分,那里有很多不错的信息。

Ah, Thomas posted the link I was looking for. 啊,托马斯发布了我正在寻找的链接。 A must read. 必须阅读。

The easiest way to check for UTF-8 validity: 检查UTF-8有效性的最简单方法是:

  1. If only one line allowed: 如果只允许一行:

     preg_match('/^.*$/Du', $value) 
  2. If multiple lines allowed: 如果允许多行:

     preg_match('/^.*$/sDu', $value) 

This works for PHP >= 4.3.5 and does not require any non-default PHP modules. 这适用于PHP> = 4.3.5 ,并且不需要任何非默认PHP模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM