r($str, 0, 1, $encoding), $encoding, \false, $lang, $try_to_keep_the_string_length); } } return $str_part_one . $str_part_two; } /** * Uppercase for all words in the string. * * EXAMPLE: UTF8::ucwords('iñt ërn âTi ônà liz æti øn'); // 'Iñt Ërn ÂTi Ônà Liz Æti Øn' * * @param string $str

The input string.

* @param string[] $exceptions [optional]

Exclusion for some words.

* @param string $char_list [optional]

Additional chars that contains to words and do not start a new * word.

* @param string $encoding [optional]

Set the charset.

* @param bool $clean_utf8 [optional]

Remove non UTF-8 chars from the string.

* * @psalm-pure * * @return string */ public static function ucwords(string $str, array $exceptions = [], string $char_list = '', string $encoding = 'UTF-8', bool $clean_utf8 = \false) : string { if (!$str) { return ''; } // INFO: mb_convert_case($str, MB_CASE_TITLE); // -> MB_CASE_TITLE didn't only uppercase the first letter, it also lowercase all other letters if ($clean_utf8) { // "mb_strpos()" and "iconv_strpos()" returns wrong position, // if invalid characters are found in $haystack before $needle $str = self::clean($str); } $use_php_default_functions = !(bool) ($char_list . \implode('', $exceptions)); if ($use_php_default_functions && ASCII::is_ascii($str)) { return \ucwords($str); } $words = self::str_to_words($str, $char_list); $use_exceptions = $exceptions !== []; $words_str = ''; foreach ($words as &$word) { if (!$word) { continue; } if (!$use_exceptions || !\in_array($word, $exceptions, \true)) { $words_str .= self::ucfirst($word, $encoding); } else { $words_str .= $word; } } return $words_str; } /** * Multi decode HTML entity + fix urlencoded-win1252-chars. * * EXAMPLE: UTF8::urldecode('tes%20öäü%20\u00edtest+test'); // 'tes öäü ítest test' * * e.g: * 'test+test' => 'test test' * 'Düsseldorf' => 'Düsseldorf' * 'D%FCsseldorf' => 'Düsseldorf' * 'Düsseldorf' => 'Düsseldorf' * 'D%26%23xFC%3Bsseldorf' => 'Düsseldorf' * 'Düsseldorf' => 'Düsseldorf' * 'D%C3%BCsseldorf' => 'Düsseldorf' * 'D%C3%83%C2%BCsseldorf' => 'Düsseldorf' * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf' * * @param string $str

The input string.

* @param bool $multi_decode

Decode as often as possible.

* * @psalm-pure * * @return string * * @template T as string * @phpstan-param T $str * @phpstan-return (T is non-empty-string ? non-empty-string : string) */ public static function urldecode(string $str, bool $multi_decode = \true) : string { if ($str === '') { return ''; } $str = self::urldecode_unicode_helper($str); if ($multi_decode) { do { $str_compare = $str; /** * @psalm-suppress PossiblyInvalidArgument */ $str = \urldecode(self::html_entity_decode(self::to_utf8($str), \ENT_QUOTES | \ENT_HTML5)); } while ($str_compare !== $str); } else { /** * @psalm-suppress PossiblyInvalidArgument */ $str = \urldecode(self::html_entity_decode(self::to_utf8($str), \ENT_QUOTES | \ENT_HTML5)); } return self::fix_simple_utf8($str); } /** * Decodes a UTF-8 string to ISO-8859-1. * * EXAMPLE: UTF8::encode('UTF-8', UTF8::utf8_decode('-ABC-中文空白-')); // '-ABC-????-' * * @param string $str

The input string.

* @param bool $keep_utf8_chars * * @psalm-pure * * @return string */ public static function utf8_decode(string $str, bool $keep_utf8_chars = \false) : string { if ($str === '') { return ''; } // save for later comparision $str_backup = $str; $len = \strlen($str); if (self::$ORD === null) { self::$ORD = self::getData('ord'); } if (self::$CHR === null) { self::$CHR = self::getData('chr'); } $no_char_found = '?'; for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) { switch ($str[$i] & "\xf0") { case "\xc0": case "\xd0": $c = self::$ORD[$str[$i] & "\x1f"] << 6 | self::$ORD[$str[++$i] & "?"]; $str[$j] = $c < 256 ? self::$CHR[$c] : $no_char_found; break; case "\xf0": ++$i; // no break case "\xe0": $str[$j] = $no_char_found; $i += 2; break; default: $str[$j] = $str[$i]; } } /** @var false|string $return - needed for PhpStan (stubs error) */ $return = \substr($str, 0, $j); if ($return === \false) { $return = ''; } if ($keep_utf8_chars && (int) self::strlen($return) >= (int) self::strlen($str_backup)) { return $str_backup; } return $return; } /** * Encodes an ISO-8859-1 string to UTF-8. * * EXAMPLE: UTF8::utf8_decode(UTF8::utf8_encode('-ABC-中文空白-')); // '-ABC-中文空白-' * * @param string $str

The input string.

* * @psalm-pure * * @return string */ public static function utf8_encode(string $str) : string { if ($str === '') { return ''; } /** @noinspection PhpUsageOfSilenceOperatorInspection | TODO for PHP > 8.2: find a replacement for this */ /** @var false|string $str - the polyfill maybe return false */ $str = @\utf8_encode($str); if ($str === \false) { return ''; } return $str; } /** * Returns an array with all utf8 whitespace characters. * * @see http://www.bogofilter.org/pipermail/bogofilter/2003-March/001889.html * * @psalm-pure * * @return string[] * An array with all known whitespace characters as values and the type of whitespace as keys * as defined in above URL */ public static function whitespace_table() : array { return self::$WHITESPACE_TABLE; } /** * Limit the number of words in a string. * * EXAMPLE: UTF8::words_limit('fòô bàř fòô', 2, ''); // 'fòô bàř' * * @param string $str

The input string.

* @param int<1, max> $limit

The limit of words as integer.

* @param string $str_add_on

Replacement for the striped string.

* * @psalm-pure * * @return string */ public static function words_limit(string $str, int $limit = 100, string $str_add_on = '…') : string { if ($str === '' || $limit <= 0) { return ''; } \preg_match('/^\\s*+(?:[^\\s]++\\s*+){1,' . $limit . '}/u', $str, $matches); if (!isset($matches[0]) || \mb_strlen($str) === (int) \mb_strlen($matches[0])) { return $str; } return \rtrim($matches[0]) . $str_add_on; } /** * Wraps a string to a given number of characters * * EXAMPLE: UTF8::wordwrap('Iñtërnâtiônàlizætiøn', 2, '
', true)); // 'Iñ
të
rn
ât
iô
nà
li
zæ
ti
øn'
* * @see http://php.net/manual/en/function.wordwrap.php * * @param string $str

The input string.

* @param int<1, max> $width [optional]

The column width.

* @param string $break [optional]

The line is broken using the optional break parameter.

* @param bool $cut [optional]

* If the cut is set to true, the string is * always wrapped at or before the specified width. So if you have * a word that is larger than the given width, it is broken apart. *

* * @psalm-pure * * @return string *

The given string wrapped at the specified column.

*/ public static function wordwrap(string $str, int $width = 75, string $break = "\n", bool $cut = \false) : string { if ($str === '' || $break === '') { return ''; } $str_split = \explode($break, $str); /** @var string[] $charsArray */ $charsArray = []; $word_split = ''; foreach ($str_split as $i => $i_value) { if ($i) { $charsArray[] = $break; $word_split .= '#'; } foreach (self::str_split($i_value) as $c) { $charsArray[] = $c; if ($c === ' ') { $word_split .= ' '; } else { $word_split .= '?'; } } } $str_return = ''; $j = 0; $b = -1; $i = -1; $word_split = \wordwrap($word_split, $width, '#', $cut); $max = \mb_strlen($word_split); /** @noinspection PhpAssignmentInConditionInspection - is ok here */ while (($b = \mb_strpos($word_split, '#', $b + 1)) !== \false) { for (++$i; $i < $b; ++$i) { if (isset($charsArray[$j])) { $str_return .= $charsArray[$j]; unset($charsArray[$j]); } ++$j; // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill if ($i > $max) { break 2; } } if ($break === $charsArray[$j] || $charsArray[$j] === ' ') { unset($charsArray[$j++]); } $str_return .= $break; // prevent endless loop, e.g. if there is a error in the "mb_*" polyfill if ($b > $max) { break; } } return $str_return . \implode('', $charsArray); } /** * Line-Wrap the string after $limit, but split the string by "$delimiter" before ... * ... so that we wrap the per line. * * @param string $str

The input string.

* @param int<1, max> $width [optional]

The column width.

* @param string $break [optional]

The line is broken using the optional break parameter.

* @param bool $cut [optional]

* If the cut is set to true, the string is * always wrapped at or before the specified width. So if you have * a word that is larger than the given width, it is broken apart. *

* @param bool $add_final_break [optional]

* If this flag is true, then the method will add a $break at the end * of the result string. *

* @param non-empty-string|null $delimiter [optional]

* You can change the default behavior, where we split the string by newline. *

* * @psalm-pure * * @return string */ public static function wordwrap_per_line(string $str, int $width = 75, string $break = "\n", bool $cut = \false, bool $add_final_break = \true, string $delimiter = null) : string { if ($delimiter === null) { $strings = \preg_split('/\\r\\n|\\r|\\n/', $str); } else { $strings = \explode($delimiter, $str); } $string_helper_array = []; if ($strings !== \false) { foreach ($strings as $value) { $string_helper_array[] = self::wordwrap($value, $width, $break, $cut); } } if ($add_final_break) { $final_break = $break; } else { $final_break = ''; } return \implode($delimiter ?? "\n", $string_helper_array) . $final_break; } /** * Returns an array of Unicode White Space characters. * * @psalm-pure * * @return string[] *

An array with numeric code point as key and White Space Character as value.

*/ public static function ws() : array { return self::$WHITESPACE; } /** * Checks whether the passed string contains only byte sequences that are valid UTF-8 characters. * * EXAMPLE: * UTF8::is_utf8_string('Iñtërnâtiônàlizætiøn']); // true * // * UTF8::is_utf8_string("Iñtërnâtiônàlizætiøn\xA0\xA1"); // false * * * @see http://hsivonen.iki.fi/php-utf8/ * * @param string $str

The string to be checked.

* @param bool $strict

Check also if the string is not UTF-16 or UTF-32.

* * @psalm-pure * * @return bool */ private static function is_utf8_string(string $str, bool $strict = \false) { if ($str === '') { return \true; } if ($strict) { $is_binary = self::is_binary($str, \true); if ($is_binary && self::is_utf16($str, \false) !== \false) { return \false; } if ($is_binary && self::is_utf32($str, \false) !== \false) { return \false; } } if (self::$SUPPORT['pcre_utf8']) { // If even just the first character can be matched, when the /u // modifier is used, then it's valid UTF-8. If the UTF-8 is somehow // invalid, nothing at all will match, even if the string contains // some valid sequences return \preg_match('/^./us', $str) === 1; } $mState = 0; // cached expected number of octets after the current octet // until the beginning of the next UTF8 character sequence $mUcs4 = 0; // cached Unicode character $mBytes = 1; // cached expected number of octets in the current sequence if (self::$ORD === null) { self::$ORD = self::getData('ord'); } $len = \strlen($str); for ($i = 0; $i < $len; ++$i) { $in = self::$ORD[$str[$i]]; if ($mState === 0) { // When mState is zero we expect either a US-ASCII character or a // multi-octet sequence. if ((0x80 & $in) === 0) { // US-ASCII, pass straight through. $mBytes = 1; } elseif ((0xe0 & $in) === 0xc0) { // First octet of 2 octet sequence. $mUcs4 = $in; $mUcs4 = ($mUcs4 & 0x1f) << 6; $mState = 1; $mBytes = 2; } elseif ((0xf0 & $in) === 0xe0) { // First octet of 3 octet sequence. $mUcs4 = $in; $mUcs4 = ($mUcs4 & 0xf) << 12; $mState = 2; $mBytes = 3; } elseif ((0xf8 & $in) === 0xf0) { // First octet of 4 octet sequence. $mUcs4 = $in; $mUcs4 = ($mUcs4 & 0x7) << 18; $mState = 3; $mBytes = 4; } elseif ((0xfc & $in) === 0xf8) { /* First octet of 5 octet sequence. * * This is illegal because the encoded codepoint must be either * (a) not the shortest form or * (b) outside the Unicode range of 0-0x10FFFF. * Rather than trying to resynchronize, we will carry on until the end * of the sequence and let the later error handling code catch it. */ $mUcs4 = $in; $mUcs4 = ($mUcs4 & 0x3) << 24; $mState = 4; $mBytes = 5; } elseif ((0xfe & $in) === 0xfc) { // First octet of 6 octet sequence, see comments for 5 octet sequence. $mUcs4 = $in; $mUcs4 = ($mUcs4 & 1) << 30; $mState = 5; $mBytes = 6; } else { // Current octet is neither in the US-ASCII range nor a legal first // octet of a multi-octet sequence. return \false; } } elseif ((0xc0 & $in) === 0x80) { // When mState is non-zero, we expect a continuation of the multi-octet // sequence // Legal continuation. $shift = ($mState - 1) * 6; $tmp = $in; $tmp = ($tmp & 0x3f) << $shift; $mUcs4 |= $tmp; // Prefix: End of the multi-octet sequence. mUcs4 now contains the final // Unicode code point to be output. if (--$mState === 0) { // Check for illegal sequences and code points. // // From Unicode 3.1, non-shortest form is illegal if ($mBytes === 2 && $mUcs4 < 0x80 || $mBytes === 3 && $mUcs4 < 0x800 || $mBytes === 4 && $mUcs4 < 0x10000 || $mBytes > 4 || ($mUcs4 & 0xfffff800) === 0xd800 || $mUcs4 > 0x10ffff) { return \false; } // initialize UTF8 cache $mState = 0; $mUcs4 = 0; $mBytes = 1; } } else { // ((0xC0 & (*in) != 0x80) && (mState != 0)) // Incomplete multi-octet sequence. return \false; } } return $mState === 0; } /** * @param string $str * @param bool $use_lowercase

Use uppercase by default, otherwise use lowercase.

* @param bool $use_full_case_fold

Convert not only common cases.

* * @psalm-pure * * @return string */ private static function fixStrCaseHelper(string $str, bool $use_lowercase = \false, bool $use_full_case_fold = \false) { $upper = self::$COMMON_CASE_FOLD['upper']; $lower = self::$COMMON_CASE_FOLD['lower']; if ($use_lowercase) { $str = \str_replace($upper, $lower, $str); } else { $str = \str_replace($lower, $upper, $str); } if ($use_full_case_fold) { /** * @psalm-suppress ImpureStaticVariable * * @var array|null */ static $FULL_CASE_FOLD = null; if ($FULL_CASE_FOLD === null) { $FULL_CASE_FOLD = self::getData('caseFolding_full'); } if ($use_lowercase) { $str = \str_replace($FULL_CASE_FOLD[0], $FULL_CASE_FOLD[1], $str); } else { $str = \str_replace($FULL_CASE_FOLD[1], $FULL_CASE_FOLD[0], $str); } } return $str; } /** * get data from "/data/*.php" * * @param string $file * * @psalm-pure * * @return array */ private static function getData(string $file) { /** @noinspection PhpIncludeInspection */ /** @noinspection UsingInclusionReturnValueInspection */ /** @psalm-suppress UnresolvableInclude */ return include __DIR__ . '/data/' . $file . '.php'; } /** * @psalm-pure * * @return true|null */ private static function initEmojiData() { if (self::$EMOJI_KEYS_CACHE === null) { if (self::$EMOJI === null) { self::$EMOJI = self::getData('emoji'); } /** * @psalm-suppress ImpureFunctionCall - static sort function is used */ \uksort(self::$EMOJI, static function (string $a, string $b) : int { return \strlen($b) <=> \strlen($a); }); self::$EMOJI_KEYS_CACHE = \array_keys(self::$EMOJI); self::$EMOJI_VALUES_CACHE = self::$EMOJI; foreach (self::$EMOJI_KEYS_CACHE as $key) { $tmp_key = \crc32($key); self::$EMOJI_KEYS_REVERSIBLE_CACHE[] = '_-_PORTABLE_UTF8_-_' . $tmp_key . '_-_' . \strrev((string) $tmp_key) . '_-_8FTU_ELBATROP_-_'; } return \true; } return null; } /** * Checks whether mbstring "overloaded" is active on the server. * * @psalm-pure * * @return bool */ private static function mbstring_overloaded() : bool { /** * INI directive 'mbstring.func_overload' is deprecated since PHP 7.2 */ /** @noinspection PhpComposerExtensionStubsInspection */ /** @noinspection PhpUsageOfSilenceOperatorInspection */ /** @noinspection DeprecatedIniOptionsInspection */ return \defined('MB_OVERLOAD_STRING') && (int) @\ini_get('mbstring.func_overload') & \MB_OVERLOAD_STRING; } /** * @param string[] $strings * @param bool $remove_empty_values * @param int|null $remove_short_values * * @psalm-pure * * @return list */ private static function reduce_string_array(array $strings, bool $remove_empty_values, int $remove_short_values = null) { // init $return = []; foreach ($strings as &$str) { if ($remove_short_values !== null && \mb_strlen($str) <= $remove_short_values) { continue; } if ($remove_empty_values && \trim($str) === '') { continue; } $return[] = $str; } return $return; } /** * rxClass * * @param string $s * @param string $class * * @return string * * @psalm-pure */ private static function rxClass(string $s, string $class = '') { /** * @psalm-suppress ImpureStaticVariable * * @var array */ static $RX_CLASS_CACHE = []; $cache_key = $s . '_' . $class; if (isset($RX_CLASS_CACHE[$cache_key])) { return $RX_CLASS_CACHE[$cache_key]; } $class_array = []; $class_array[] = $class; /** @noinspection SuspiciousLoopInspection */ /** @noinspection AlterInForeachInspection */ foreach (self::str_split($s) as &$s) { if ($s === '-') { $class_array[0] = '-' . $class_array[0]; } elseif (!isset($s[2])) { $class_array[0] .= \preg_quote($s, '/'); } elseif (self::strlen($s) === 1) { $class_array[0] .= $s; } else { $class_array[] = $s; } } if ($class_array[0]) { $class_array[0] = '[' . $class_array[0] . ']'; } if (\count($class_array) === 1) { $return = $class_array[0]; } else { $return = '(?:' . \implode('|', $class_array) . ')'; } $RX_CLASS_CACHE[$cache_key] = $return; return $return; } /** * Personal names such as "Marcus Aurelius" are sometimes typed incorrectly using lowercase ("marcus aurelius"). * * @param string $names * @param string $delimiter * @param string $encoding * * @phpstan-param non-empty-string $delimiter * * @psalm-pure * * @return string */ private static function str_capitalize_name_helper(string $names, string $delimiter, string $encoding = 'UTF-8') { // init try { $name_helper_array = \explode($delimiter, $names); } catch (\Error $e) { // PHP >= 8.0 : explode() will now throw ValueError when separator parameter is given an empty string (""). Previously, explode() returned false instead. $name_helper_array = \false; } if ($name_helper_array === \false) { return ''; } $special_cases = ['names' => ['ab', 'af', 'al', 'and', 'ap', 'bint', 'binte', 'da', 'de', 'del', 'den', 'der', 'di', 'dit', 'ibn', 'la', 'mac', 'nic', 'of', 'ter', 'the', 'und', 'van', 'von', 'y', 'zu'], 'prefixes' => ['al-', "d'", 'ff', "l'", 'mac', 'mc', 'nic']]; foreach ($name_helper_array as &$name) { if (\in_array($name, $special_cases['names'], \true)) { continue; } $continue = \false; if ($delimiter === '-') { foreach ((array) $special_cases['names'] as &$beginning) { if (\strncmp($name, $beginning, \strlen($beginning)) === 0) { $continue = \true; break; } } unset($beginning); } foreach ((array) $special_cases['prefixes'] as &$beginning) { if (\strncmp($name, $beginning, \strlen($beginning)) === 0) { $continue = \true; break; } } unset($beginning); if ($continue) { continue; } $name = self::ucfirst($name, $encoding); } return \implode($delimiter, $name_helper_array); } /** * Generic case-sensitive transformation for collation matching. * * @param string $str

The input string

* * @psalm-pure * * @return string|null */ private static function strtonatfold(string $str) { $str = \Normalizer::normalize($str, \Normalizer::NFD); if ($str === \false) { return ''; } return \preg_replace('/\\p{Mn}+/u', '', $str); } /** * @param int|string $input * * @psalm-pure * * @return string */ private static function to_utf8_convert_helper($input) { // init $buf = ''; if (self::$ORD === null) { self::$ORD = self::getData('ord'); } if (self::$CHR === null) { self::$CHR = self::getData('chr'); } if (self::$WIN1252_TO_UTF8 === null) { self::$WIN1252_TO_UTF8 = self::getData('win1252_to_utf8'); } $ordC1 = self::$ORD[$input]; if (isset(self::$WIN1252_TO_UTF8[$ordC1])) { // found in Windows-1252 special cases $buf .= self::$WIN1252_TO_UTF8[$ordC1]; } else { $cc1 = self::$CHR[$ordC1 / 64] | "\xc0"; $cc2 = (string) $input & "?" | "\x80"; $buf .= $cc1 . $cc2; } return $buf; } /** * @param string $str * * @psalm-pure * * @return string */ private static function urldecode_unicode_helper(string $str) { if (\strpos($str, '%u') === \false) { return $str; } $pattern = '/%u([0-9a-fA-F]{3,4})/'; if (\preg_match($pattern, $str)) { $str = (string) \preg_replace($pattern, '&#x\\1;', $str); } return $str; } }