А именно, как бы вы рассказали строку, которая содержит бинарные данные из данных text ? Я пытаюсь реализовать: < /p>
[*] Полный php < /strong> solution < /li>
с Нет внешние библиотеки
[*] кодирование-aware
[*] согласованно
и быстро < /strong> достаточно, чтобы справиться с длинными потоками < /li>
< /ul>
Вот лучшее решение, которое я столкнулся (среди всех неработающих), которое опирается на MBString Семейство функций:
function isBinaryStream(string $stream) : bool {
// 1) Try to detect encoding
// $encoding is a prioritized list of encodings (from less widely used to most widely used) for many Western and East Asian applications
$encoding = mb_detect_encoding($stream, [
'UTF-8', 'GB18030', 'BIG-5', 'EUC-JP', 'SJIS', 'ASCII', 'Windows-1252', 'ISO-8859-1', 'Windows-1251', 'KOI8-R',
], true);
if ($encoding !== 'UTF-8') {
$stream = mb_convert_encoding($stream, 'UTF-8', $encoding);
}
// 2) Split into characters and convert to code points
$chars = mb_str_split($stream, 1, 'UTF-8');
if (! $chars) {
return true;
}
$ordValues = array_map('mb_ord', $chars);
// 3) Disallow control chars except \t(9), \n(10), \r(13) and disallow code points above 0x10FFFF (invalid Unicode)
foreach ($ordValues as $ord) {
if ($ord < 0x20 && ! in_array($ord, [9, 10, 13], true)) {
return true;
}
if ($ord > 0x10FFFF) {
return true;
}
}
// If we are here, we consider $stream textual
return false;
}
< /code>
попытался спросить AI, но его реализация дала мне много ложных срабатываний на огромном наборе текстовых файлов, которые содержали разреженные ошибочные символы. < /p>
// ATTENTION: this code is AI-generated. Don't blindly copy-paste it.
function syntheticIsBinaryStream(string $stream) : bool {
// ATTENTION: this code is AI-generated. Don't blindly copy-paste it.
// Define a prioritized list of encodings.
$encodings = ['UTF-8', 'ASCII', 'Windows-1252', 'ISO-8859-1'];
$validEncoding = false;
foreach ($encodings as $enc) {
// Strict check: only return true if the sample is valid in the encoding.
if (mb_check_encoding($stream, $enc)) {
$validEncoding = $enc;
break;
}
}
if ($validEncoding === false) {
// If none of our encodings validate the sample, assume binary.
return true;
}
// If encoding is not UTF-8, convert to UTF-8 for consistent further processing.
if ($validEncoding !== 'UTF-8') {
$stream = mb_convert_encoding($stream, 'UTF-8', $validEncoding);
}
// Now, count disallowed control characters (any Cc that is not tab, newline, or carriage return)
// Using Unicode properties, this regex matches any control char except \r, \n, \t.
if (preg_match_all('/[\p{Cc}&&[^\r\n\t]]/u', $stream, $matches)) {
$controlCount = count($matches[0]);
} else {
$controlCount = 0;
}
// Compute total number of characters in the stream.
$totalChars = mb_strlen($stream, 'UTF-8');
if ($totalChars === 0) {
return true;
}
$ratio = $controlCount / $totalChars;
// If the ratio of disallowed control characters is above 10%, we consider the sample as binary.
return $ratio > 0.10;
}
< /code>
также попробовал это решение с ctype_print, и это также дало мне много ложных срабатываний. < /p>
факт, я чувствую, что моя реализация IsbinaryStream
Отсутствие последовательности. Я не совсем уверен, что это будет работать только для текстовых потоков на незападных кодировках. Кроме того, я клянусь, что это может быть чрезвычайно оптимизировано. < /P>
Что вы предлагаете? Спасибо за совет.
А именно, как бы вы рассказали строку, которая содержит бинарные данные из данных text ? Я пытаюсь реализовать: < /p>
[*] [b] Полный php < /strong> solution < /li> с Нет [/b] внешние библиотеки [*] кодирование-aware [*] согласованно и быстро < /strong> достаточно, чтобы справиться с длинными потоками < /li> < /ul> Вот лучшее решение, которое я столкнулся (среди всех неработающих), которое опирается на MBString Семейство функций: [code]function isBinaryStream(string $stream) : bool { // 1) Try to detect encoding // $encoding is a prioritized list of encodings (from less widely used to most widely used) for many Western and East Asian applications $encoding = mb_detect_encoding($stream, [ 'UTF-8', 'GB18030', 'BIG-5', 'EUC-JP', 'SJIS', 'ASCII', 'Windows-1252', 'ISO-8859-1', 'Windows-1251', 'KOI8-R', ], true); if ($encoding !== 'UTF-8') { $stream = mb_convert_encoding($stream, 'UTF-8', $encoding); }
// 2) Split into characters and convert to code points $chars = mb_str_split($stream, 1, 'UTF-8'); if (! $chars) { return true; } $ordValues = array_map('mb_ord', $chars);
// 3) Disallow control chars except \t(9), \n(10), \r(13) and disallow code points above 0x10FFFF (invalid Unicode) foreach ($ordValues as $ord) { if ($ord < 0x20 && ! in_array($ord, [9, 10, 13], true)) { return true; } if ($ord > 0x10FFFF) { return true; } }
// If we are here, we consider $stream textual return false; } < /code> попытался спросить AI, но его реализация дала мне много ложных срабатываний на огромном наборе текстовых файлов, которые содержали разреженные ошибочные символы. < /p> // ATTENTION: this code is AI-generated. Don't blindly copy-paste it. function syntheticIsBinaryStream(string $stream) : bool { // ATTENTION: this code is AI-generated. Don't blindly copy-paste it.
// Define a prioritized list of encodings. $encodings = ['UTF-8', 'ASCII', 'Windows-1252', 'ISO-8859-1']; $validEncoding = false; foreach ($encodings as $enc) { // Strict check: only return true if the sample is valid in the encoding. if (mb_check_encoding($stream, $enc)) { $validEncoding = $enc; break; } }
if ($validEncoding === false) { // If none of our encodings validate the sample, assume binary. return true; }
// If encoding is not UTF-8, convert to UTF-8 for consistent further processing. if ($validEncoding !== 'UTF-8') { $stream = mb_convert_encoding($stream, 'UTF-8', $validEncoding); }
// Now, count disallowed control characters (any Cc that is not tab, newline, or carriage return) // Using Unicode properties, this regex matches any control char except \r, \n, \t. if (preg_match_all('/[\p{Cc}&&[^\r\n\t]]/u', $stream, $matches)) { $controlCount = count($matches[0]); } else { $controlCount = 0; }
// Compute total number of characters in the stream. $totalChars = mb_strlen($stream, 'UTF-8'); if ($totalChars === 0) { return true; } $ratio = $controlCount / $totalChars;
// If the ratio of disallowed control characters is above 10%, we consider the sample as binary. return $ratio > 0.10; } < /code> также попробовал это решение с ctype_print, и это также дало мне много ложных срабатываний. < /p> факт, я чувствую, что моя реализация IsbinaryStream [/code] Отсутствие последовательности. Я не совсем уверен, что это будет работать только для текстовых потоков на незападных кодировках. Кроме того, я клянусь, что это может быть чрезвычайно оптимизировано. < /P> Что вы предлагаете? Спасибо за совет.
Я работаю над университетским проектом, включающим двоичные деревья, представленные в виде словарей. Я реализовал функции для проверки того, являются ли эти деревья полными, завершенными и двоичными, но моя проверка двоичного дерева не работает...
Я работаю над университетским проектом, включающим двоичные деревья, представленные в виде словарей. Я реализовал функции для проверки того, являются ли эти деревья полными, завершенными и двоичными, но моя проверка двоичного дерева не работает...