Skip to content

Commit

Permalink
[~]: optimize "UTF8::is_binary()" + more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
voku committed Dec 24, 2016
1 parent d98de59 commit cd7fbc3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/voku/helper/UTF8.php
Expand Up @@ -2737,20 +2737,16 @@ public static function is_base64($str)
*/
public static function is_binary($input)
{
if (preg_match('~^[01]+$~', $input)) {
return true;
}

$testLength = strlen($input);

if (
preg_match('~^[01]+$~', $input)
||
substr_count($input, "\x00") > 0
||
($testLength ? substr_count($input, '^ -~') / $testLength > 0.3 : 1 === 0)
) {
if (substr_count($input, "\x0") / $testLength > 0.3) {
return true;
} else {
return false;
}

return false;
}

/**
Expand Down
12 changes: 12 additions & 0 deletions tests/Utf8GlobalTest.php
Expand Up @@ -1365,8 +1365,20 @@ public function testIsBinary()
'枚盲眉' => false,
'' => false,
'1' => false,
'01010101' => true,
decbin(324546) => true,
01 => true,
1020304 => false,
01020304 => false,
11020304 => false,
'1010101' => true,
11111111 => true,
00000000 => true,
"\x00\x01" => true,
"\x01\x00" => true,
"\x01\x02" => false,
"\x01\x00ab" => false, // <= 30% binary
"\x01\x00a" => true, // >= 30% binary
);

foreach ($tests as $before => $after) {
Expand Down

0 comments on commit cd7fbc3

Please sign in to comment.