Skip to content

Instantly share code, notes, and snippets.

@m3m0r7
Last active March 25, 2023 12:27
Show Gist options
  • Save m3m0r7/23f448c7ed9269e4be0f to your computer and use it in GitHub Desktop.
Save m3m0r7/23f448c7ed9269e4be0f to your computer and use it in GitHub Desktop.
<?php
/**
* mb_count_chars
* @author @memory-agape
* @param string $string The examined string
* @param int $mode
* @return array|string
*/
function mb_count_chars ($string, $mode = 0) {
$result = array_fill(0, 256, 0);
for ($i = 0, $size = mb_strlen($string); $i < $size; $i++) {
$char = mb_substr($string, $i, 1);
if (strlen($char) > 1) {
continue;
}
$code = ord($char);
if ($code >= 0 && $code <= 255) {
$result[$code]++;
}
}
switch ($mode) {
case 1: // same as 0 but only byte-values with a frequency greater than zero are listed.
foreach ($result as $key => $value) {
if ($value == 0) {
unset($result[$key]);
}
}
break;
case 2: // same as 0 but only byte-values with a frequency equal to zero are listed.
foreach ($result as $key => $value) {
if ($value > 0) {
unset($result[$key]);
}
}
break;
case 3: // a string containing all unique characters is returned.
$buildString = '';
foreach ($result as $key => $value) {
if ($value > 0) {
$buildString .= chr($key);
}
}
return $buildString;
case 4: // a string containing all not used characters is returned.
$buildString = '';
foreach ($result as $key => $value) {
if ($value == 0) {
$buildString .= chr($key);
}
}
return $buildString;
}
// change key names...
foreach ($result as $key => $value) {
$result[chr($key)] = $value;
unset($result[$key]);
}
return $result;
}
@MathiasReker
Copy link

MathiasReker commented Mar 25, 2023

Hello

Nice function. FYI: I have created a library including mb_count_chars: https://github.com/MathiasReker/php-mbstring-extension

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment