* This file is part of the Symfony package.
* (c) Fabien Potencier <fabien@symfony.com>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
namespace Symfony\Polyfill\Mbstring;
* Partial mbstring implementation in PHP, iconv based, UTF-8 centric.
* - mb_chr - Returns a specific character from its Unicode code point
* - mb_convert_encoding - Convert character encoding
* - mb_convert_variables - Convert character code in variable(s)
* - mb_decode_mimeheader - Decode string in MIME header field
* - mb_encode_mimeheader - Encode string for MIME header XXX NATIVE IMPLEMENTATION IS REALLY BUGGED
* - mb_decode_numericentity - Decode HTML numeric string reference to character
* - mb_encode_numericentity - Encode character to HTML numeric string reference
* - mb_convert_case - Perform case folding on a string
* - mb_detect_encoding - Detect character encoding
* - mb_get_info - Get internal settings of mbstring
* - mb_http_input - Detect HTTP input character encoding
* - mb_http_output - Set/Get HTTP output character encoding
* - mb_internal_encoding - Set/Get internal character encoding
* - mb_list_encodings - Returns an array of all supported encodings
* - mb_ord - Returns the Unicode code point of a character
* - mb_output_handler - Callback function converts character encoding in output buffer
* - mb_scrub - Replaces ill-formed byte sequences with substitute characters
* - mb_strlen - Get string length
* - mb_strpos - Find position of first occurrence of string in a string
* - mb_strrpos - Find position of last occurrence of a string in a string
* - mb_str_split - Convert a string to an array
* - mb_strtolower - Make a string lowercase
* - mb_strtoupper - Make a string uppercase
* - mb_substitute_character - Set/Get substitution character
* - mb_substr - Get part of string
* - mb_stripos - Finds position of first occurrence of a string within another, case insensitive
* - mb_stristr - Finds first occurrence of a string within another, case insensitive
* - mb_strrchr - Finds the last occurrence of a character in a string within another
* - mb_strrichr - Finds the last occurrence of a character in a string within another, case insensitive
* - mb_strripos - Finds position of last occurrence of a string within another, case insensitive
* - mb_strstr - Finds first occurrence of a string within another
* - mb_strwidth - Return width of string
* - mb_substr_count - Count the number of substring occurrences
* - mb_convert_kana - Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
* - mb_ereg_* - Regular expression with multibyte support
* - mb_parse_str - Parse GET/POST/COOKIE data and set global variable
* - mb_preferred_mime_name - Get MIME charset string
* - mb_regex_encoding - Returns current encoding for multibyte regex as string
* - mb_regex_set_options - Set/Get the default options for mbregex functions
* - mb_send_mail - Send encoded mail
* - mb_split - Split multibyte string using regular expression
* - mb_strcut - Get part of string
* - mb_strimwidth - Get truncated string with specified width
* @author Nicolas Grekas <p@tchwork.com>
const MB_CASE_FOLD = PHP_INT_MAX;
private static $encodingList = array('ASCII', 'UTF-8');
private static $language = 'neutral';
private static $internalEncoding = 'UTF-8';
private static $caseFold = array(
array('µ', 'ſ', "\xCD\x85", 'ς', "\xCF\x90", "\xCF\x91", "\xCF\x95", "\xCF\x96", "\xCF\xB0", "\xCF\xB1", "\xCF\xB5", "\xE1\xBA\x9B", "\xE1\xBE\xBE"),
array('μ', 's', 'ι', 'σ', 'β', 'θ', 'φ', 'π', 'κ', 'ρ', 'ε', "\xE1\xB9\xA1", 'ι'),
public static function mb_convert_encoding($s, $toEncoding, $fromEncoding = null)
if (\is_array($fromEncoding) || false !== strpos($fromEncoding, ',')) {
$fromEncoding = self::mb_detect_encoding($s, $fromEncoding);
$fromEncoding = self::getEncoding($fromEncoding);
$toEncoding = self::getEncoding($toEncoding);
if ('BASE64' === $fromEncoding) {
$fromEncoding = $toEncoding;
if ('BASE64' === $toEncoding) {
return base64_encode($s);
if ('HTML-ENTITIES' === $toEncoding || 'HTML' === $toEncoding) {
if ('HTML-ENTITIES' === $fromEncoding || 'HTML' === $fromEncoding) {
$fromEncoding = 'Windows-1252';
if ('UTF-8' !== $fromEncoding) {
$s = iconv($fromEncoding, 'UTF-8//IGNORE', $s);
return preg_replace_callback('/[\x80-\xFF]+/', array(__CLASS__, 'html_encoding_callback'), $s);
if ('HTML-ENTITIES' === $fromEncoding) {
$s = html_entity_decode($s, ENT_COMPAT, 'UTF-8');
return iconv($fromEncoding, $toEncoding.'//IGNORE', $s);
public static function mb_convert_variables($toEncoding, $fromEncoding, &$a = null, &$b = null, &$c = null, &$d = null, &$e = null, &$f = null)
$vars = array(&$a, &$b, &$c, &$d, &$e, &$f);
array_walk_recursive($vars, function (&$v) use (&$ok, $toEncoding, $fromEncoding) {
if (false === $v = Mbstring::mb_convert_encoding($v, $toEncoding, $fromEncoding)) {
return $ok ? $fromEncoding : false;
public static function mb_decode_mimeheader($s)
return iconv_mime_decode($s, 2, self::$internalEncoding);
public static function mb_encode_mimeheader($s, $charset = null, $transferEncoding = null, $linefeed = null, $indent = null)
trigger_error('mb_encode_mimeheader() is bugged. Please use iconv_mime_encode() instead', E_USER_WARNING);
public static function mb_decode_numericentity($s, $convmap, $encoding = null)
if (null !== $s && !\is_scalar($s) && !(\is_object($s) && \method_exists($s, '__toString'))) {
trigger_error('mb_decode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', E_USER_WARNING);
if (!\is_array($convmap) || !$convmap) {
if (null !== $encoding && !\is_scalar($encoding)) {
trigger_error('mb_decode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', E_USER_WARNING);
return ''; // Instead of null (cf. mb_encode_numericentity).
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding) {
if (!preg_match('//u', $s)) {
$s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
$s = iconv($encoding, 'UTF-8//IGNORE', $s);
$cnt = floor(\count($convmap) / 4) * 4;
for ($i = 0; $i < $cnt; $i += 4) {
// collector_decode_htmlnumericentity ignores $convmap[$i + 3]
$convmap[$i] += $convmap[$i + 2];
$convmap[$i + 1] += $convmap[$i + 2];
$s = preg_replace_callback('/&#(?:0*([0-9]+)|x0*([0-9a-fA-F]+))(?!&);?/', function (array $m) use ($cnt, $convmap) {
$c = isset($m[2]) ? (int) hexdec($m[2]) : $m[1];
for ($i = 0; $i < $cnt; $i += 4) {
if ($c >= $convmap[$i] && $c <= $convmap[$i + 1]) {
return Mbstring::mb_chr($c - $convmap[$i + 2]);
if (null === $encoding) {
return iconv('UTF-8', $encoding.'//IGNORE', $s);
public static function mb_encode_numericentity($s, $convmap, $encoding = null, $is_hex = false)
if (null !== $s && !\is_scalar($s) && !(\is_object($s) && \method_exists($s, '__toString'))) {
trigger_error('mb_encode_numericentity() expects parameter 1 to be string, '.\gettype($s).' given', E_USER_WARNING);
if (!\is_array($convmap) || !$convmap) {
if (null !== $encoding && !\is_scalar($encoding)) {
trigger_error('mb_encode_numericentity() expects parameter 3 to be string, '.\gettype($s).' given', E_USER_WARNING);
return null; // Instead of '' (cf. mb_decode_numericentity).
if (null !== $is_hex && !\is_scalar($is_hex)) {
trigger_error('mb_encode_numericentity() expects parameter 4 to be boolean, '.\gettype($s).' given', E_USER_WARNING);
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding) {
if (!preg_match('//u', $s)) {
$s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
$s = iconv($encoding, 'UTF-8//IGNORE', $s);
static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4);
$cnt = floor(\count($convmap) / 4) * 4;
$ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
$uchr = substr($s, $i, $ulen);
$c = self::mb_ord($uchr);
for ($j = 0; $j < $cnt; $j += 4) {
if ($c >= $convmap[$j] && $c <= $convmap[$j + 1]) {
$cOffset = ($c + $convmap[$j + 2]) & $convmap[$j + 3];
$result .= $is_hex ? sprintf('&#x%X;', $cOffset) : '&#'.$cOffset.';';
if (null === $encoding) {
return iconv('UTF-8', $encoding.'//IGNORE', $result);
public static function mb_convert_case($s, $mode, $encoding = null)
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding) {
if (!preg_match('//u', $s)) {
$s = @iconv('UTF-8', 'UTF-8//IGNORE', $s);
$s = iconv($encoding, 'UTF-8//IGNORE', $s);
if (MB_CASE_TITLE == $mode) {
static $titleRegexp = null;
if (null === $titleRegexp) {
$titleRegexp = self::getData('titleCaseRegexp');
$s = preg_replace_callback($titleRegexp, array(__CLASS__, 'title_case'), $s);
if (MB_CASE_UPPER == $mode) {
$upper = self::getData('upperCase');
if (self::MB_CASE_FOLD === $mode) {
$s = str_replace(self::$caseFold[0], self::$caseFold[1], $s);
$lower = self::getData('lowerCase');
static $ulenMask = array("\xC0" => 2, "\xD0" => 2, "\xE0" => 3, "\xF0" => 4);
$ulen = $s[$i] < "\x80" ? 1 : $ulenMask[$s[$i] & "\xF0"];
$uchr = substr($s, $i, $ulen);
if (isset($map[$uchr])) {
$s[--$nlen] = $uchr[--$ulen];
$s = substr_replace($s, $uchr, $i - $ulen, $ulen);
if (null === $encoding) {
return iconv('UTF-8', $encoding.'//IGNORE', $s);
public static function mb_internal_encoding($encoding = null)
if (null === $encoding) {
return self::$internalEncoding;
$encoding = self::getEncoding($encoding);
if ('UTF-8' === $encoding || false !== @iconv($encoding, $encoding, ' ')) {
self::$internalEncoding = $encoding;
public static function mb_language($lang = null)
switch ($lang = strtolower($lang)) {
public static function mb_list_encodings()
public static function mb_encoding_aliases($encoding)
switch (strtoupper($encoding)) {
public static function mb_check_encoding($var = null, $encoding = null)
if (null === $encoding) {
$encoding = self::$internalEncoding;
return self::mb_detect_encoding($var, array($encoding)) || false !== @iconv($encoding, $encoding, $var);
public static function mb_detect_encoding($str, $encodingList = null, $strict = false)
if (null === $encodingList) {
$encodingList = self::$encodingList;
if (!\is_array($encodingList)) {
$encodingList = array_map('trim', explode(',', $encodingList));
$encodingList = array_map('strtoupper', $encodingList);
foreach ($encodingList as $enc) {
if (!preg_match('/[\x80-\xFF]/', $str)) {
if (preg_match('//u', $str)) {
if (0 === strncmp($enc, 'ISO-8859-', 9)) {
public static function mb_detect_order($encodingList = null)
if (null === $encodingList) {
return self::$encodingList;
if (!\is_array($encodingList)) {
$encodingList = array_map('trim', explode(',', $encodingList));
$encodingList = array_map('strtoupper', $encodingList);
foreach ($encodingList as $enc) {
if (strncmp($enc, 'ISO-8859-', 9)) {
self::$encodingList = $encodingList;
public static function mb_strlen($s, $encoding = null)
$encoding = self::getEncoding($encoding);
if ('CP850' === $encoding || 'ASCII' === $encoding) {
return @iconv_strlen($s, $encoding);
public static function mb_strpos($haystack, $needle, $offset = 0, $encoding = null)
$encoding = self::getEncoding($encoding);
if ('CP850' === $encoding || 'ASCII' === $encoding) {
return strpos($haystack, $needle, $offset);
$needle = (string) $needle;
trigger_error(__METHOD__.': Empty delimiter', E_USER_WARNING);