我正在尝试将一些鱼类信息配置文件从使用 latin1
字符集的定制 CMS 转移到使用 UTF 的 WordPress 自定义(自定义帖子类型,具有大量元字段)数据库-8
.
最重要的是,旧的 CMS 使用了一些奇怪的 bbCode 位。
基本上,我正在寻找一个可以执行此操作的函数:
- 使用
latin1_swedish_ci
归类(和latin1
字符集)从我的旧数据库中获取信息 - 将所有非标准字符(我们有来自克罗地亚语、捷克语、西类牙语、法语和德语等语言的字符)转换为 HTML 实体,如
á
(数字如&134;
也很好)。 - 将所有 bbCode(见下文)转换为 HTML
- 将
'
和"
转换为 HTML 实体 - 返回
utf-8
字符集的信息到我的新数据库
bbCode to
和 from
是:
$search = array( '[i]', '[/i]', '[b]', '[/b]', '[pl]', '[/pl]' );
$replace = array( '<i>', '</i>', '<strong>', '</strong>', '', '' );
到目前为止我尝试过的功能是:
$search = array( '[i]', '[/i]', '[b]', '[/b]', '[pl]', '[/pl]' );
$replace = array( '<i>', '</i>', '<strong>', '</strong>', '', '' );
function _convert($content) {
if(!mb_check_encoding($content, 'UTF-8')
OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {
$content = mb_convert_encoding($content, 'UTF-8');
if (mb_check_encoding($content, 'UTF-8')) {
return $content;
} else {
echo "<p>Couldn't convert to UTF-8.</p>";
}
}
}
function _clean($content) {
$content = _convert( $content );
/* edited out because otherwise all HTML appears as <html> rather than <html>
//$content = htmlentities( $content, ENT_QUOTES, "UTF-8" );
$content = str_replace( $search, $replace, $content );
return $content;
}
然而,这会阻止某些字段被导入到新数据库中,并且不会替换 bbCode。
如果我使用下面的代码,它基本上可以工作:
$var = str_replace( $search, $replace, htmlentities( $row["var"], ENT_QUOTES, "UTF-8"));
但是,某些包含我认为是捷克语/克罗地亚语字符的字段根本不会出现。
有没有人对我如何按照上面列出的顺序将信息从“旧格式”成功转换为新格式有任何建议?
最佳答案
我会说,如果您想转换所有非 ASCII 字符,您将不需要进行任何 latin1
到 UTF-8
的转换。假设您对数据运行 htmlspecialchars
或 htmlentities
等函数,然后所有非 ASCII 字符都将替换为其相应的实体代码。
基本上,在这一步之后,应该没有任何字符需要转换为 UTF-8
。此外,如果您想将 latin1
编码字符串转换为 UTF-8
,我强烈怀疑 utf8_encode
会很好。
附言。在将 bbCode
转换为 HTML
时,我建议改用正则表达式。例如,您可以像这样在一行中完成所有操作:
$html_data = preg_replace('/\[(/?[a-z]+)\]/i', '<$1>', $bb_code_data);
关于php - 迁移数据,从 latin1 字符集到 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9088910/