在 PHP 中是否有任何方法可以检测以下字符 �
?
我目前正在使用几种不同的算法解决一些 UTF-8 编码问题,并且需要能够检测字符串中是否存在 �
。我如何使用 strpos
做到这一点?
简单地将角色粘贴到我的代码库中似乎不起作用。
if (strpos($names['decode'], '?') !== false || strpos($names['decode'], '�') !== false)
最佳答案
使用 iconv()
和 //IGNORE
参数将 UTF-8 字符串转换为 UTF-8 会产生丢弃无效 UTF-8 字符的结果。
因此,您可以通过比较 iconv 操作前后的字符串长度来检测断字符。如果它们不同,则它们包含损坏的字符。
测试用例(确保将文件保存为 UTF-8):
<?php
header("Content-type: text/html; charset=utf-8");
$teststring = "Düsseldorf";
// Deliberately create broken string
// by encoding the original string as ISO-8859-1
$teststring_broken = utf8_decode($teststring);
echo "Broken string: ".$teststring_broken ;
echo "<br>";
$teststring_converted = iconv("UTF-8", "UTF-8//IGNORE", $teststring_broken );
echo $teststring_converted;
echo "<br>";
if (strlen($teststring_converted) != strlen($teststring_broken ))
echo "The string contained an invalid character";
理论上,您可以删除 //IGNORE
并简单地测试失败的(空的)iconv
操作,但 iconv 失败可能还有其他原因只是无效字符...我不知道。我会使用比较法。
关于php - PHP中Unicode未知 "�"字符检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4536986/