protected static function mbStrReplaceInternal(
        $search,
        $replace,
        $subject,
        $caseInsensitive = false,
        $encoding = self::DEFAULT_ENCODING,
        &$count = null
    ) {
        $searchLength = mb_strlen($search, $encoding);
        $subjectLength = mb_strlen($subject, $encoding);
        $offset = 0;
        $result = '';

        while ($offset < $subjectLength) {
            $match = $caseInsensitive
                ? mb_stripos($subject, $search, $offset, $encoding)
                : mb_strpos($subject, $search, $offset, $encoding);
            if ($match === false) {
                if ($offset === 0) {
                    // No match was ever found, just return the subject.
                    return $subject;
                }
                // Append the final portion of the subject to the replaced.
                $result .= mb_substr($subject, $offset, $subjectLength - $offset, $encoding);
                break;
            }
            if ($count !== null) {
                $count++;
            }
            $result .= mb_substr($subject, $offset, $match - $offset, $encoding);
            $result .= $replace;
            $offset = $match + $searchLength;
        }

        return $result;
    }