Symfony\Polyfill\Mbstring

Mbstring::utf8 │ private static │ CF7 1.0

Converts $s to UTF-8 to search it, ending with "\xFF", a byte that is invalid in UTF-8, when its last sequence is truncated, like native mbstring.

Метод класса: Mbstring{}

Хуков нет.

Возвращает

string|false. False when the encoding is unknown

Использование

$result = Mbstring::utf8( $s, $encoding, $dropped );
$s(строка) (обязательный)
.
$encoding(строка) (обязательный)
.
$dropped(int) (передается по ссылке — &)
Set to the number of bytes of the ill-formed sequences that iconv() dropped elsewhere.

Код Mbstring::utf8() CF7 6.2.4.1

private static function utf8(string $s, string $encoding, &$dropped = 0)
{
    if ('UTF-8' === $encoding || '' === $s) {
        return $s;
    }

    if (false !== $u = @iconv($encoding, 'UTF-8', $s)) {
        return $u;
    }

    // Let iconv() warn about an unknown encoding
    if (false === iconv($encoding, 'UTF-8', '')) {
        return false;
    }

    // iconv() drops the ill-formed sequences, but fails on a truncated one at the end
    for ($i = 0; $i < 4; ++$i) {
        if (false !== $u = @self::iconv($encoding, 'UTF-8', $i ? substr($s, 0, -$i) : $s)) {
            $dropped = \strlen($s) - $i - \strlen((string) @iconv('UTF-8', $encoding, $u));

            return $i || '' === $u ? $u."\xFF" : $u;
        }
    }

    $dropped = \strlen($s);

    return "\xFF";
}