PHP中的Unicode未知" "字符检测

Jam*_*mes 7 php unicode utf-8 utf8-decode

在PHP中有没有办法检测以下字符?

我目前正在使用一些不同的算法修复一些UTF-8编码问题,并且需要能够检测?字符串中是否存在.我该怎么办strpos

简单地将角色粘贴到我的代码库中似乎不起作用.

if (strpos($names['decode'], '?') !== false || strpos($names['decode'], '?') !== false)
Run Code Online (Sandbox Code Playgroud)

Pek*_*ica 17

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";
Run Code Online (Sandbox Code Playgroud)

从理论上讲,你可以放弃//IGNORE并简单地测试失败的(空的)iconv操作,但是iconv失败可能还有其他原因而不仅仅是无效的字符...我不知道.我会用比较方法.