我正在处理一个大型文本文件,其名称偶尔会有特殊字符。一个例子是“CASTA¥EDA,JASON”。当我处理文件时,该行以UTF-8形式出现。但是,当Mongo的插入即将发生时,它会显示错误:
class B;
class A {
public:
B func( int x ); // declared
B func2() { return B{}; } // this would not compile with forward declaration of B
};
class B {
};
// this definition must see class B defined, not forward declared
B A::func( int x )
{
return B{};
}
然后我继续这样做:
[MongoDB\Driver\Exception\UnexpectedValueException]
Got invalid UTF-8 value serializing 'Jason Casta�eda'
现在这产生了:Jason Castaeda
有没有办法查找名称是否包含非utf-8的特殊字符。
理想情况下,知道一行文件是否包含不会切割到Mongo的字符会很好。有什么提示吗?
我的意思是我之前可以使用名称的长度,然后执行iconv并比较字符串长度,但这似乎微不足道。有更好的方法吗?
答案 0 :(得分:1)
我建议转换所有用户输入字符串into a Buffer。
或者使用ACKNOWLEDGED
编辑: 对不起,完全忽略了php标签。试试这个:
function bin2text($your_binary_number) {
$text_str = '';
$chars = explode("\n", chunk_split(str_replace("\n", '', $bin_str), 8));
$_i = count($chars);
for ($i = 0; $i < $_i; $text_str .= chr(bindec($chars[$i])), $i );
return $text_str;
}
function text2bin($txt_str) {
$len = strlen($txt_str);
$bin = '';
for($i = 0; $i < $len; $i )
{
$bin .= strlen(decbin(ord($txt_str[$i]))) < 8 ? str_pad(decbin(ord($txt_str[$i])), 8, 0, str_pad_left) : decbin(ord($txt_str[$i]));
}
return $bin;
}
取自:http://psoug.org/snippet/PHP-Binary-to-Text-Text-to-Binary_380.htm
text2bin
基本上将您的字符串转换为二进制文件,bin2text()
将二进制文件转换回文本