php - PHP中Unicode未知 "�"字符检测

标签 php unicode utf-8 utf8-decode

在 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/

相关文章:

unicode - 在 Windows 上显示 U+FFFF 上方的 Unicode 字符

string - 使用 Perl 从字符串中删除 BOM

当检测到非 UTF8 字符时,PHP preg_replace() 失败

php - Composer : How to override a requirement globally for composer. json?

php - Pear Mail "Unable to find class for driver smtp"找不到文件,就在那里

php - 如何从 wp 主题 wp_dequeue_script 或 wp_deregister_script jquery (不受影响)文件

php - 只有 1 个用户访问本地 Intranet 页面被拒绝

c++ - 这是什么 ?在读取使用 Unicode 编码的文本文件后控制台输出的开头?

unicode - Common Lisp 中 unicode 字符的语法(如果有)是什么?

java - java中如何解决这个编码问题