<li>Jain R.K. and Iyengar S.R.K., “Advanced Engineering Mathematicsâ€, Narosa Publications,</li>
我在数据库中有很多原始 html 字符串。所有的文字都有这些奇怪的字符。我怎样才能将其转换为普通文本以将其保存回数据库中。
$final = '<li>Jain R.K. and Iyengar S.R.K., “Advanced Engineering Mathematicsâ€, Narosa Publications,</li>';
$final = utf8_encode($final);
$final = htmlspecialchars_decode($final);
$final = html_entity_decode($final, ENT_QUOTES, "UTF-8");
$final = utf8_decode($final);
echo $final;
我试过上面的代码,它在网络浏览器中正确显示,但仍然在数据库中保存相同的奇怪字符。
数据库的字符集是utf-8
“
是 “
的“Mojibake”。您可以尝试避免使用非 ascii 引号,但这只会延迟再次陷入麻烦。
您需要在表格和连接中使用
utf8mb4
。有关 Mojibake 的可能原因,请参阅this。
$final = '<li>Jain R.K. and Iyengar S.R.K., “Advanced Engineering Mathematicsâ€, Narosa Publications,</li>';
$final = str_replace("Â", "", $final);
$final = str_replace("’", "'", $final);
$final = str_replace("“", '"', $final);
$final = str_replace('–', '-', $final);
$final = str_replace('â€', '"', $final);
对于过去的数据,我用UTF-8字符替换了奇怪的字符。
对于未来的数据,我在 php、html 和数据库连接中将字符集设置为 utf8。
使用ftfy工具修复文本更安全https://ftfy.readthedocs.io/en/latest/
我知道这已经得到解答,但我遇到了同样的问题并通过修复表中的字符集以供将来输入数据来修复它。
我正在使用 SQL Server 2017,排序规则设置为
SQL_Latin1_General_CP1_CI_AS
对于现有字符,我编写了一个脚本来从数据库中提取数据并搜索匹配并修复这些字符的每个字符。
我创建了两个 csv,一个包含带有杂散字符的数据(email_templates.csv"),另一个包含干净的 html 模板(clean_templates.csv)。
要查找文本/html 中的杂散字符,您也可以使用此在线工具,这非常有帮助。
https://freetools.textmagic.com/unicode-detector
UTF-8编码调试图
https://www.i18nqa.com/debug/utf8-debug.html
HTML代码和HTML特殊字符
https://psdtowp.net/html-codes-special-characters.html
为了在 VS Code 中验证相同内容,我使用了扩展程序
Render Special Characters
下面是链接。
https://marketplace.visualstudio.com/items?itemName=miku3920.vscode-render-special-chars
用于验证和修复问题的 PHP 脚本
$fileName = "email_templates.csv";
$ofileName = "clean_templates.csv";
try {
$stray_chars = array(
'—' => '-',
'–' => '-',
'‘'=> '\'',
'’' => '\'',
'“' => '"' ,
'â€' => '"',
'Â'=>'',
'ó'=> "ó",
"ñ" => "ñ",
"Ã" => "í",
"á"=> "á",
"" => '',
);
$contents = getEmailTemplateContent();
$handle = fopen($fileName, "w") or die('Unable to open file');
$ohandle = fopen($ofileName, "w") or die('Unable to open file');
$data = [];
$cleaned = [];
$i = 0;
$html = '';
foreach($contents as $content) {
$html = $content['html'];
$clean = str_replace(array_keys($stray_chars), array_values($stray_chars), $html);
$cleaned[$i] = $content['id']."-xxxx-".$clean;
$data[$i] = $content['id']."-xxxx-".$html;
//Fix stray characters in database
updateEmailTemplateContent($clean, $content['id']);
$i++;
}
fputcsv($handle, $data);
fputcsv($ohandle, $cleaned);
fclose($handle);
fclose($ohandle);
}
catch(\PDOException $e) {
$jobStatus = 'E';
$jobError = $e->getMessage();
}