Skip to content

Instantly share code, notes, and snippets.

@pospi
Created September 24, 2013 01:56
Show Gist options
  • Save pospi/6679410 to your computer and use it in GitHub Desktop.
Save pospi/6679410 to your computer and use it in GitHub Desktop.
Get reliable byte length of a string in PHP. Works around an issue where the multibyte string extension can be configured to shadow strlen().
<?php
/**
* Works around an issue where the multibyte string extension
* can be configured to shadow strlen(), and no longer returns pure
* bytelength.
* @param string $str string to get byte length of
* @return int
*/
function bytelen($str)
{
static $has_mbstring = extension_loaded('mbstring');
static $has_mb_shadow = (int) ini_get('mbstring.func_overload');
if ($has_mbstring && ($has_mb_shadow & 2)) {
return mb_strlen($str, 'latin1');
} else {
return strlen($str);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment