[optional]
Remove non UTF-8 chars from the * string.
* @param string|null $lang [optional]Set the language for special cases: az, * el, lt, tr
* @param bool $try_to_keep_the_string_length [optional]true === try to keep the string length: * e.g. ẞ -> ß
* @param bool $use_trim_first [optional]true === trim the input string, * first
* @param string|null $word_define_chars [optional]An string of chars that will be used as * whitespace separator === words.
* * @psalm-pure * * @return string *The titleized string.
*/ public static function str_titleize( string $str, ?array $ignore = null, string $encoding = 'UTF-8', bool $clean_utf8 = false, ?string $lang = null, bool $try_to_keep_the_string_length = false, bool $use_trim_first = true, ?string $word_define_chars = null ): string { if ($str === '') { return ''; } if ($encoding !== 'UTF-8' && $encoding !== 'CP850') { $encoding = self::normalize_encoding($encoding, 'UTF-8'); } if ($use_trim_first) { $str = \trim($str); } if ($clean_utf8) { $str = self::clean($str); } $use_mb_functions = $lang === null && !$try_to_keep_the_string_length; if ($word_define_chars) { $word_define_chars = \preg_quote($word_define_chars, '/'); } else { $word_define_chars = ''; } $str = (string) \preg_replace_callback( '/([^\\s' . $word_define_chars . ']+)/u', static function (array $match) use ($try_to_keep_the_string_length, $lang, $ignore, $use_mb_functions, $encoding): string { if ($ignore !== null && \in_array($match[0], $ignore, true)) { return $match[0]; } if ($use_mb_functions) { if ($encoding === 'UTF-8') { return \mb_strtoupper(\mb_substr($match[0], 0, 1)) . \mb_strtolower(\mb_substr($match[0], 1)); } return \mb_strtoupper(\mb_substr($match[0], 0, 1, $encoding), $encoding) . \mb_strtolower(\mb_substr($match[0], 1, null, $encoding), $encoding); } return self::ucfirst( self::strtolower( $match[0], $encoding, false, $lang, $try_to_keep_the_string_length ), $encoding, false, $lang, $try_to_keep_the_string_length ); }, $str ); return $str; } /** * Convert a string into a obfuscate string. * * EXAMPLE:
*
* UTF8::str_obfuscate('lars@moelleken.org', 0.5, '*', ['@', '.']); // e.g. "l***@m**lleke*.*r*"
*
*
* @param string $str
* @param float $percent
* @param string $obfuscateChar
* @param string[] $keepChars
*
* @psalm-pure
*
* @return string
* The obfuscate string.
*/ public static function str_obfuscate( string $str, float $percent = 0.5, string $obfuscateChar = '*', array $keepChars = [] ): string { $obfuscateCharHelper = "\u{2603}"; $str = \str_replace($obfuscateChar, $obfuscateCharHelper, $str); $chars = self::chars($str); $charsMax = \count($chars); $charsMaxChange = \round($charsMax * $percent); $charsCounter = 0; $charKeyDone = []; while ($charsCounter < $charsMaxChange) { foreach ($chars as $charKey => $char) { if (isset($charKeyDone[$charKey])) { continue; } if (\random_int(0, 100) > 50) { continue; } if ($char === $obfuscateChar) { continue; } ++$charsCounter; $charKeyDone[$charKey] = true; if ($charsCounter > $charsMaxChange) { break; } if (\in_array($char, $keepChars, true)) { continue; } $chars[$charKey] = $obfuscateChar; } } $str = \implode('', $chars); return \str_replace($obfuscateCharHelper, $obfuscateChar, $str); } /** * Returns a trimmed string in proper title case. * * Also accepts an array, $ignore, allowing you to list words not to be * capitalized. * * Adapted from John Gruber's script. * * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78 * * @param string $str * @param string[] $ignoreAn array of words not to capitalize.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return string *The titleized string.
*/ public static function str_titleize_for_humans( string $str, array $ignore = [], string $encoding = 'UTF-8' ): string { if ($str === '') { return ''; } $small_words = [ '(? In-Flight $str = (string) \preg_replace_callback( '~\\b (? "Stand-In" (Stand is already capped at this point) $str = (string) \preg_replace_callback( '~\\b (?UTF8::str_to_binary('😃'); // '11110000100111111001100010000011' * * @param string $strThe input string.
* * @psalm-pure * * @return false|string *false on error
*/ public static function str_to_binary(string $str) { $value = \unpack('H*', $str); if ($value === false) { return false; } return \base_convert($value[1], 16, 2); } /** * @param string $str * @param bool $remove_empty_valuesRemove empty values.
* @param int|null $remove_short_valuesThe min. string length or null to disable
* * @psalm-pure * * @return string[] */ public static function str_to_lines(string $str, bool $remove_empty_values = false, ?int $remove_short_values = null): array { if ($str === '') { return $remove_empty_values ? [] : ['']; } if (self::$SUPPORT['mbstring'] === true) { $return = \mb_split("[\r\n]{1,2}", $str); } else { $return = \preg_split("/[\r\n]{1,2}/u", $str); } if ($return === false) { return $remove_empty_values ? [] : ['']; } if ( $remove_short_values === null && !$remove_empty_values ) { return $return; } return self::reduce_string_array( $return, $remove_empty_values, $remove_short_values ); } /** * Convert a string into an array of words. * * EXAMPLE:UTF8::str_to_words('中文空白 oöäü#s', '#') // array('', '中文空白', ' ', 'oöäü#s', '')
*
* @param string $str
* @param string $char_list Additional chars for the definition of "words".
* @param bool $remove_empty_valuesRemove empty values.
* @param int|null $remove_short_valuesThe min. string length or null to disable
* * @psalm-pure * * @return listDesired length of the truncated string.
* @param string $substring [optional]The substring to append if it can fit. Default: ''
* @param string $encoding [optional]Default: 'UTF-8'
* * @psalm-pure * * @return string *A string after truncating.
*/ public static function str_truncate( string $str, int $length, string $substring = '', string $encoding = 'UTF-8' ): string { if ($str === '') { return ''; } if ($encoding === 'UTF-8') { if ($length >= (int) \mb_strlen($str)) { return $str; } if ($substring !== '') { $length -= (int) \mb_strlen($substring); /** @noinspection UnnecessaryCastingInspection */ return (string) \mb_substr($str, 0, $length) . $substring; } return (string) \mb_substr($str, 0, $length); } $encoding = self::normalize_encoding($encoding, 'UTF-8'); if ($length >= (int) self::strlen($str, $encoding)) { return $str; } if ($substring !== '') { $length -= (int) self::strlen($substring, $encoding); } return ( (string) self::substr( $str, 0, $length, $encoding ) ) . $substring; } /** * Truncates the string to a given length, while ensuring that it does not * split words. If $substring is provided, and truncating occurs, the * string is further truncated so that the substring may be appended without * exceeding the desired length. * * @param string $str * @param int $lengthDesired length of the truncated string.
* @param string $substring [optional]The substring to append if it can fit. * Default: * ''
* @param string $encoding [optional]Default: 'UTF-8'
* @param bool $ignore_do_not_split_words_for_one_word [optional]Default: false
* * @psalm-pure * * @return string *A string after truncating.
*/ public static function str_truncate_safe( string $str, int $length, string $substring = '', string $encoding = 'UTF-8', bool $ignore_do_not_split_words_for_one_word = false ): string { if ($str === '' || $length <= 0) { return $substring; } if ($encoding === 'UTF-8') { if ($length >= (int) \mb_strlen($str)) { return $str; } // need to further trim the string so we can append the substring $length -= (int) \mb_strlen($substring); if ($length <= 0) { return $substring; } /** @var false|string $truncated - needed for PhpStan (stubs error) */ $truncated = \mb_substr($str, 0, $length); if ($truncated === false) { return ''; } // if the last word was truncated $space_position = \mb_strpos($str, ' ', $length - 1); if ($space_position !== $length) { // find pos of the last occurrence of a space, get up to that $last_position = \mb_strrpos($truncated, ' ', 0); if ( $last_position !== false || ( $space_position !== false && !$ignore_do_not_split_words_for_one_word ) ) { $truncated = (string) \mb_substr($truncated, 0, (int) $last_position); } } } else { $encoding = self::normalize_encoding($encoding, 'UTF-8'); if ($length >= (int) self::strlen($str, $encoding)) { return $str; } // need to further trim the string so we can append the substring $length -= (int) self::strlen($substring, $encoding); if ($length <= 0) { return $substring; } $truncated = self::substr($str, 0, $length, $encoding); if ($truncated === false) { return ''; } // if the last word was truncated $space_position = self::strpos($str, ' ', $length - 1, $encoding); if ($space_position !== $length) { // find pos of the last occurrence of a space, get up to that $last_position = self::strrpos($truncated, ' ', 0, $encoding); if ( $last_position !== false || ( $space_position !== false && !$ignore_do_not_split_words_for_one_word ) ) { $truncated = (string) self::substr($truncated, 0, (int) $last_position, $encoding); } } } return $truncated . $substring; } /** * Returns a lowercase and trimmed string separated by underscores. * Underscores are inserted before uppercase characters (with the exception * of the first character of the string), and in place of spaces as well as * dashes. * * @param string $str * * @psalm-pure * * @return string *The underscored string.
*/ public static function str_underscored(string $str): string { return self::str_delimit($str, '_'); } /** * Returns an UpperCamelCase version of the supplied string. It trims * surrounding spaces, capitalizes letters following digits, spaces, dashes * and underscores, and removes spaces, dashes, underscores. * * @param string $strThe input string.
* @param string $encoding [optional]Default: 'UTF-8'
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* @param string|null $lang [optional]Set the language for special cases: az, el, lt, * tr
* @param bool $try_to_keep_the_string_length [optional]true === try to keep the string length: e.g. ẞ * -> ß
* * @psalm-pure * * @return string *A string in UpperCamelCase.
*/ public static function str_upper_camelize( string $str, string $encoding = 'UTF-8', bool $clean_utf8 = false, ?string $lang = null, bool $try_to_keep_the_string_length = false ): string { return self::ucfirst(self::str_camelize($str, $encoding), $encoding, $clean_utf8, $lang, $try_to_keep_the_string_length); } /** * Get the number of words in a specific string. * * EXAMPLES:
* // format: 0 -> return only word count (int)
* //
* UTF8::str_word_count('中文空白 öäü abc#c'); // 4
* UTF8::str_word_count('中文空白 öäü abc#c', 0, '#'); // 3
*
* // format: 1 -> return words (array)
* //
* UTF8::str_word_count('中文空白 öäü abc#c', 1); // array('中文空白', 'öäü', 'abc', 'c')
* UTF8::str_word_count('中文空白 öäü abc#c', 1, '#'); // array('中文空白', 'öäü', 'abc#c')
*
* // format: 2 -> return words with offset (array)
* //
* UTF8::str_word_count('中文空白 öäü ab#c', 2); // array(0 => '中文空白', 5 => 'öäü', 9 => 'abc', 13 => 'c')
* UTF8::str_word_count('中文空白 öäü ab#c', 2, '#'); // array(0 => '中文空白', 5 => 'öäü', 9 => 'abc#c')
*
*
* @param string $str The input string.
* @param int $format [optional]
* 0 => return a number of words (default)
* 1 => return an array of words
* 2 => return an array of words with word-offset as key
*
Additional chars that contains to words and do not start a new word.
* * @psalm-pure * * @return int|string[] *The number of words in the string.
* * @phpstan-param 0|1|2 $format * @phpstan-return ($format is 2 ? arrayUTF8::strcasecmp("iñtërnâtiôn\nàlizætiøn", "Iñtërnâtiôn\nàlizætiøn"); // 0
*
* @param string $str1 The first string.
* @param string $str2The second string.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return int * < 0 if str1 is less than str2;UTF8::strcmp("iñtërnâtiôn\nàlizætiøn", "iñtërnâtiôn\nàlizætiøn"); // 0
*
* @param string $str1 The first string.
* @param string $str2The second string.
* * @psalm-pure * * @return int * < 0 if str1 is less than str2Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return int * * @phpstan-return 0|positive-int */ public static function strcspn( string $str, string $char_list, int $offset = 0, ?int $length = null, string $encoding = 'UTF-8' ): int { if ($encoding !== 'UTF-8' && $encoding !== 'CP850') { $encoding = self::normalize_encoding($encoding, 'UTF-8'); } if ($char_list === '') { return (int) self::strlen($str, $encoding); } if ($offset || $length !== null) { if ($encoding === 'UTF-8') { if ($length === null) { $str_tmp = \mb_substr($str, $offset); } else { $str_tmp = \mb_substr($str, $offset, $length); } } else { $str_tmp = self::substr($str, $offset, $length, $encoding); } if ($str_tmp === false) { return 0; } $str = $str_tmp; } if ($str === '') { return 0; } $matches = []; if (\preg_match('/^(.*?)' . self::rxClass($char_list) . '/us', $str, $matches)) { $return = self::strlen($matches[1], $encoding); if ($return === false) { return 0; } return $return; } return (int) self::strlen($str, $encoding); } /** * Create a UTF-8 string from code points. * * INFO: opposite to UTF8::codepoints() * * EXAMPLE:UTF8::string(array(246, 228, 252)); // 'öäü'
*
* @param int|int[]|string|string[] $intOrHex Integer or Hexadecimal codepoints.
* * @phpstan-param int[]|numeric-string[]|int|numeric-string $intOrHex * * @psalm-pure * * @return string *A UTF-8 encoded string.
*/ public static function string($intOrHex): string { if ($intOrHex === []) { return ''; } if (!\is_array($intOrHex)) { $intOrHex = [$intOrHex]; } $str = ''; foreach ($intOrHex as $strPart) { $str .= '' . (int) $strPart . ';'; } // We cannot use html_entity_decode() here, as it will not return // characters for many values < 160. return mb_convert_encoding($str, 'UTF-8', 'HTML-ENTITIES'); } /** * Checks if string starts with "BOM" (Byte Order Mark Character) character. * * EXAMPLE:UTF8::string_has_bom("\xef\xbb\xbf foobar"); // true
*
* @param string $str The input string.
* * @psalm-pure * * @return bool *
* true if the string has BOM at the start,
* false otherwise
*
UTF8::strip_tags("κόσμε\xa0\xa1"); // 'κόσμε'
*
* @see http://php.net/manual/en/function.strip-tags.php
*
* @param string $str * The input string. *
* @param string|null $allowable_tags [optional]* You can use the optional second parameter to specify tags which should * not be stripped. *
** HTML comments and PHP tags are also stripped. This is hardcoded and * can not be changed with allowable_tags. *
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return string *The stripped string.
*/ public static function strip_tags( string $str, ?string $allowable_tags = null, bool $clean_utf8 = false ): string { if ($str === '') { return ''; } if ($clean_utf8) { $str = self::clean($str); } if ($allowable_tags === null) { return \strip_tags($str); } return \strip_tags($str, $allowable_tags); } /** * Strip all whitespace characters. This includes tabs and newline * characters, as well as multibyte whitespace such as the thin space * and ideographic space. * * EXAMPLE:UTF8::strip_whitespace(' Ο συγγραφέας '); // 'Οσυγγραφέας'
*
* @param string $str
*
* @psalm-pure
*
* @return string
*/
public static function strip_whitespace(string $str): string
{
if ($str === '') {
return '';
}
return (string) \preg_replace('/[[:space:]]+/u', '', $str);
}
/**
* Find the position of the first occurrence of a substring in a string, case-insensitive.
*
* INFO: use UTF8::stripos_in_byte() for the byte-length
*
* EXAMPLE: UTF8::stripos('aσσb', 'ΣΣ'); // 1 (σσ == ΣΣ)
*
* @see http://php.net/manual/en/function.mb-stripos.php
*
* @param string $haystack The string from which to get the position of the first occurrence of needle.
* @param string $needleThe string to find in haystack.
* @param int $offset [optional]The position in haystack to start searching.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|int * Return the (int) numeric position of the first occurrence of needle in the * haystack string,
* $str = 'iñtërnâtiônàlizætiøn';
* $search = 'NÂT';
*
* UTF8::stristr($str, $search)); // 'nâtiônàlizætiøn'
* UTF8::stristr($str, $search, true)); // 'iñtër'
*
*
* @param string $haystack The input string. Must be valid UTF-8.
* @param string $needleThe string to look for. Must be valid UTF-8.
* @param bool $before_needle [optional]* If TRUE, it returns the part of the * haystack before the first occurrence of the needle (excluding the needle). *
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|string *A sub-string,
or false if needle is not found.
UTF8::strlen("Iñtërnâtiôn\xE9àlizætiøn")); // 20
*
* @see http://php.net/manual/en/function.mb-strlen.php
*
* @param string $str The string being checked for length.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|int *
* The number (int) of characters in the string $str having character encoding
* $encoding.
* (One multi-byte character counted as +1).
*
* Can return false, if e.g. mbstring is not installed and we process invalid
* chars.
*
* UTF8::strnatcasecmp('2', '10Hello WORLD 中文空白!'); // -1
* UTF8::strcasecmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // 1
*
* UTF8::strnatcasecmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // 1
* UTF8::strcasecmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // -1
*
*
* @param string $str1 The first string.
* @param string $str2The second string.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return int * < 0 if str1 is less than str2
* UTF8::strnatcmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // -1
* UTF8::strcmp('2Hello world 中文空白!', '10Hello WORLD 中文空白!'); // 1
*
* UTF8::strnatcmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // 1
* UTF8::strcmp('10Hello world 中文空白!', '2Hello WORLD 中文空白!'); // -1
*
*
* @see http://php.net/manual/en/function.strnatcmp.php
*
* @param string $str1 The first string.
* @param string $str2The second string.
* * @psalm-pure * * @return int * < 0 if str1 is less than str2;
* UTF8::strcasecmp("iñtërnâtiôn\nàlizætiøn321", "iñtërnâtiôn\nàlizætiøn123", 5); // 0
*
*
* @see http://php.net/manual/en/function.strncasecmp.php
*
* @param string $str1 The first string.
* @param string $str2The second string.
* @param int $lenThe length of strings to be used in the comparison.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return int * < 0 if str1 is less than str2;
* UTF8::strncmp("Iñtërnâtiôn\nàlizætiøn321", "Iñtërnâtiôn\nàlizætiøn123", 5); // 0
*
*
* @see http://php.net/manual/en/function.strncmp.php
*
* @param string $str1 The first string.
* @param string $str2The second string.
* @param int $lenNumber of characters to use in the comparison.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return int * < 0 if str1 is less than str2;UTF8::strpbrk('-中文空白-', '白'); // '白-'
*
* @see http://php.net/manual/en/function.strpbrk.php
*
* @param string $haystack The string where char_list is looked for.
* @param string $char_listThis parameter is case-sensitive.
* * @psalm-pure * * @return false|string *The string starting from the character found, or false if it is not found.
*/ public static function strpbrk(string $haystack, string $char_list) { if ($haystack === '' || $char_list === '') { return false; } if (\preg_match('/' . self::rxClass($char_list) . '/us', $haystack, $m)) { return \substr($haystack, (int) \strpos($haystack, $m[0])); } return false; } /** * Find the position of the first occurrence of a substring in a string. * * INFO: use UTF8::strpos_in_byte() for the byte-length * * EXAMPLE:UTF8::strpos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 8
*
* @see http://php.net/manual/en/function.mb-strpos.php
*
* @param string $haystack The string from which to get the position of the first occurrence of needle.
* @param int|string $needleThe string to find in haystack.
Or a code point as int.
The search offset. If it is not specified, 0 is used.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|int * The (int) numeric position of the first occurrence of needle in the haystack * string.* The string being checked. *
* @param string $needle* The position counted from the beginning of haystack. *
* @param int $offset [optional]* The search offset. If it is not specified, 0 is used. *
* * @psalm-pure * * @return false|int *The numeric position of the first occurrence of needle in the * haystack string. If needle is not found, it returns false.
* * @phpstan-return false|0|positive-int */ public static function strpos_in_byte(string $haystack, string $needle, int $offset = 0) { if ($haystack === '' || $needle === '') { return false; } if (self::$SUPPORT['mbstring_func_overload'] === true) { // "mb_" is available if overload is used, so use it ... return \mb_strpos($haystack, $needle, $offset, 'CP850'); // 8-BIT } return \strpos($haystack, $needle, $offset); } /** * Find the position of the first occurrence of a substring in a string, case-insensitive. * * @param string $haystack* The string being checked. *
* @param string $needle* The position counted from the beginning of haystack. *
* @param int $offset [optional]* The search offset. If it is not specified, 0 is used. *
* * @psalm-pure * * @return false|int *The numeric position of the first occurrence of needle in the * haystack string. If needle is not found, it returns false.
* * @phpstan-return false|0|positive-int */ public static function stripos_in_byte(string $haystack, string $needle, int $offset = 0) { if ($haystack === '' || $needle === '') { return false; } if (self::$SUPPORT['mbstring_func_overload'] === true) { // "mb_" is available if overload is used, so use it ... return \mb_stripos($haystack, $needle, $offset, 'CP850'); // 8-BIT } return \stripos($haystack, $needle, $offset); } /** * Find the last occurrence of a character in a string within another. * * EXAMPLE:UTF8::strrchr('κόσμεκόσμε-äöü', 'κόσμε'); // 'κόσμε-äöü'
*
* @see http://php.net/manual/en/function.mb-strrchr.php
*
* @param string $haystack The string from which to get the last occurrence of needle.
* @param string $needleThe string to find in haystack
* @param bool $before_needle [optional]* Determines which portion of haystack * this function returns. * If set to true, it returns all of haystack * from the beginning to the last occurrence of needle. * If set to false, it returns all of haystack * from the last occurrence of needle to the end, *
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|string *The portion of haystack or false if needle is not found.
*/ public static function strrchr( string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $clean_utf8 = false ) { if ($haystack === '' || $needle === '') { return false; } if ($encoding !== 'UTF-8' && $encoding !== 'CP850') { $encoding = self::normalize_encoding($encoding, 'UTF-8'); } if ($clean_utf8) { // "mb_strpos()" and "iconv_strpos()" returns wrong position, // if invalid characters are found in $haystack before $needle $needle = self::clean($needle); $haystack = self::clean($haystack); } // // fallback via mbstring // if (self::$SUPPORT['mbstring'] === true) { if ($encoding === 'UTF-8') { return \mb_strrchr($haystack, $needle, $before_needle); } return \mb_strrchr($haystack, $needle, $before_needle, $encoding); } // // fallback for binary || ascii only // if ( !$before_needle && ( $encoding === 'CP850' || $encoding === 'ASCII' ) ) { return \strrchr($haystack, $needle); } if ( $encoding !== 'UTF-8' && self::$SUPPORT['mbstring'] === false ) { /** * @psalm-suppress ImpureFunctionCall - this is only a warning */ \trigger_error('UTF8::strrchr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING); } // // fallback via iconv // if (self::$SUPPORT['iconv'] === true) { $needle_tmp = self::substr($needle, 0, 1, $encoding); if ($needle_tmp === false) { return false; } $needle = $needle_tmp; $pos = \iconv_strrpos($haystack, $needle, $encoding); if ($pos === false) { return false; } if ($before_needle) { return self::substr($haystack, 0, $pos, $encoding); } return self::substr($haystack, $pos, null, $encoding); } // // fallback via vanilla php // $needle_tmp = self::substr($needle, 0, 1, $encoding); if ($needle_tmp === false) { return false; } $needle = $needle_tmp; $pos = self::strrpos($haystack, $needle, 0, $encoding); if ($pos === false) { return false; } if ($before_needle) { return self::substr($haystack, 0, $pos, $encoding); } return self::substr($haystack, $pos, null, $encoding); } /** * Reverses characters order in the string. * * EXAMPLE:UTF8::strrev('κ-öäü'); // 'üäö-κ'
*
* @param string $str The input string.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return string *The string with characters in the reverse sequence.
*/ public static function strrev(string $str, string $encoding = 'UTF-8'): string { if ($str === '') { return ''; } // init $reversed = ''; $str = self::emoji_encode($str, true); if ($encoding === 'UTF-8') { if (self::$SUPPORT['intl'] === true) { // try "grapheme" first: https://stackoverflow.com/questions/17496493/strrev-dosent-support-utf-8 $i = (int) \grapheme_strlen($str); while ($i--) { $reversed_tmp = \grapheme_substr($str, $i, 1); if ($reversed_tmp !== false) { $reversed .= $reversed_tmp; } } } else { $i = (int) \mb_strlen($str); while ($i--) { $reversed_tmp = \mb_substr($str, $i, 1); if ($reversed_tmp !== false) { /* @phpstan-ignore-line | old polyfill will return false, or? */ $reversed .= $reversed_tmp; } } } } else { $encoding = self::normalize_encoding($encoding, 'UTF-8'); $i = (int) self::strlen($str, $encoding); while ($i--) { $reversed_tmp = self::substr($str, $i, 1, $encoding); if ($reversed_tmp !== false) { $reversed .= $reversed_tmp; } } } return self::emoji_decode($reversed, true); } /** * Find the last occurrence of a character in a string within another, case-insensitive. * * EXAMPLE:UTF8::strrichr('Aκόσμεκόσμε-äöü', 'aκόσμε'); // 'Aκόσμεκόσμε-äöü'
*
* @see http://php.net/manual/en/function.mb-strrichr.php
*
* @param string $haystack The string from which to get the last occurrence of needle.
* @param string $needleThe string to find in haystack.
* @param bool $before_needle [optional]* Determines which portion of haystack * this function returns. * If set to true, it returns all of haystack * from the beginning to the last occurrence of needle. * If set to false, it returns all of haystack * from the last occurrence of needle to the end, *
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|string *The portion of haystack or
false if needle is not found.
UTF8::strripos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 13
*
* @param string $haystack The string to look in.
* @param int|string $needleThe string to look for.
* @param int $offset [optional]Number of characters to ignore in the beginning or end.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|int *The (int) numeric position of the last occurrence of needle in the haystack
* string.
If needle is not found, it returns false.
* The string from which to get the position of the last occurrence * of needle. *
* @param string $needle* The string to find in haystack. *
* @param int $offset [optional]* The position in haystack * to start searching. *
* * @psalm-pure * * @return false|int *eturn the numeric position of the last occurrence of needle in the * haystack string, or false if needle is not found.
*/ public static function strripos_in_byte(string $haystack, string $needle, int $offset = 0) { if ($haystack === '' || $needle === '') { return false; } if (self::$SUPPORT['mbstring_func_overload'] === true) { // "mb_" is available if overload is used, so use it ... return \mb_strripos($haystack, $needle, $offset, 'CP850'); // 8-BIT } return \strripos($haystack, $needle, $offset); } /** * Find the position of the last occurrence of a substring in a string. * * EXAMPLE:UTF8::strrpos('ABC-ÖÄÜ-中文空白-中文空白', '中'); // 13
*
* @see http://php.net/manual/en/function.mb-strrpos.php
*
* @param string $haystack The string being checked, for the last occurrence of needle
* @param int|string $needleThe string to find in haystack.
Or a code point as int.
May be specified to begin searching an arbitrary number of characters * into the string. Negative values will stop searching at an arbitrary point prior to * the end of the string. *
* @param string $encoding [optional]Set the charset.
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|int *The (int) numeric position of the last occurrence of needle in the haystack
* string.
If needle is not found, it returns false.
* The string being checked, for the last occurrence * of needle. *
* @param string $needle* The string to find in haystack. *
* @param int $offset [optional]May be specified to begin searching an arbitrary number of characters into * the string. Negative values will stop searching at an arbitrary point * prior to the end of the string. *
* * @psalm-pure * * @return false|int *The numeric position of the last occurrence of needle in the * haystack string. If needle is not found, it returns false.
*/ public static function strrpos_in_byte(string $haystack, string $needle, int $offset = 0) { if ($haystack === '' || $needle === '') { return false; } if (self::$SUPPORT['mbstring_func_overload'] === true) { // "mb_" is available if overload is used, so use it ... return \mb_strrpos($haystack, $needle, $offset, 'CP850'); // 8-BIT } return \strrpos($haystack, $needle, $offset); } /** * Finds the length of the initial segment of a string consisting entirely of characters contained within a given * mask. * * EXAMPLE:UTF8::strspn('iñtërnâtiônàlizætiøn', 'itñ'); // '3'
*
* @param string $str The input string.
* @param string $maskThe mask of chars
* @param int $offset [optional] * @param int|null $length [optional] * @param string $encoding [optional]Set the charset.
* * @psalm-pure * * @return false|int */ public static function strspn( string $str, string $mask, int $offset = 0, ?int $length = null, string $encoding = 'UTF-8' ) { if ($encoding !== 'UTF-8' && $encoding !== 'CP850') { $encoding = self::normalize_encoding($encoding, 'UTF-8'); } if ($offset || $length !== null) { if ($encoding === 'UTF-8') { if ($length === null) { $str = (string) \mb_substr($str, $offset); } else { $str = (string) \mb_substr($str, $offset, $length); } } else { $str = (string) self::substr($str, $offset, $length, $encoding); } } if ($str === '' || $mask === '') { return 0; } $matches = []; return \preg_match('/^' . self::rxClass($mask) . '+/u', $str, $matches) ? (int) self::strlen($matches[0], $encoding) : 0; } /** * Returns part of haystack string from the first occurrence of needle to the end of haystack. * * EXAMPLE:
* $str = 'iñtërnâtiônàlizætiøn';
* $search = 'nât';
*
* UTF8::strstr($str, $search)); // 'nâtiônàlizætiøn'
* UTF8::strstr($str, $search, true)); // 'iñtër'
*
*
* @param string $haystack The input string. Must be valid UTF-8.
* @param string $needleThe string to look for. Must be valid UTF-8.
* @param bool $before_needle [optional]* If TRUE, strstr() returns the part of the * haystack before the first occurrence of the needle (excluding the needle). *
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|string *A sub-string,
or false if needle is not found.
* The string from which to get the first occurrence * of needle. *
* @param string $needle* The string to find in haystack. *
* @param bool $before_needle [optional]* Determines which portion of haystack * this function returns. * If set to true, it returns all of haystack * from the beginning to the first occurrence of needle. * If set to false, it returns all of haystack * from the first occurrence of needle to the end, *
* * @psalm-pure * * @return false|string *The portion of haystack, * or false if needle is not found.
*/ public static function strstr_in_byte( string $haystack, string $needle, bool $before_needle = false ) { if ($haystack === '' || $needle === '') { return false; } if (self::$SUPPORT['mbstring_func_overload'] === true) { // "mb_" is available if overload is used, so use it ... return \mb_strstr($haystack, $needle, $before_needle, 'CP850'); // 8-BIT } return \strstr($haystack, $needle, $before_needle); } /** * Unicode transformation for case-less matching. * * EXAMPLE:UTF8::strtocasefold('ǰ◌̱'); // 'ǰ◌̱'
*
* @see http://unicode.org/reports/tr21/tr21-5.html
*
* @param string $str The input string.
* @param bool $full [optional]
* true, replace full case folding chars (default)
* false, use only limited static array [UTF8::$COMMON_CASE_FOLD]
*
Remove non UTF-8 chars from the string.
* @param string $encoding [optional]Set the charset.
* @param string|null $lang [optional]Set the language for special cases: az, el, lt, tr
* @param bool $lower [optional]Use lowercase string, otherwise use uppercase string. PS: uppercase * is for some languages better ...
* * @psalm-pure * * @return string */ public static function strtocasefold( string $str, bool $full = true, bool $clean_utf8 = false, string $encoding = 'UTF-8', ?string $lang = null, bool $lower = true ): string { if ($str === '') { return ''; } if ($clean_utf8) { // "mb_strpos()" and "iconv_strpos()" returns wrong position, // if invalid characters are found in $haystack before $needle $str = self::clean($str); } $str = self::fixStrCaseHelper($str, $lower, $full); if ($lang === null && $encoding === 'UTF-8') { if ($lower) { return \mb_strtolower($str); } return \mb_strtoupper($str); } if ($lower) { return self::strtolower($str, $encoding, false, $lang); } return self::strtoupper($str, $encoding, false, $lang); } /** * Make a string lowercase. * * EXAMPLE:UTF8::strtolower('DÉJÀ Σσς Iıİi'); // 'déjà σσς iıii'
*
* @see http://php.net/manual/en/function.mb-strtolower.php
*
* @param string $str The string being lowercased.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* @param string|null $lang [optional]Set the language for special cases: az, el, lt, * tr
* @param bool $try_to_keep_the_string_length [optional]true === try to keep the string length: e.g. ẞ * -> ß
* * @psalm-pure * * @return string *String with all alphabetic characters converted to lowercase.
*/ public static function strtolower( $str, string $encoding = 'UTF-8', bool $clean_utf8 = false, ?string $lang = null, bool $try_to_keep_the_string_length = false ): string { // init $str = (string) $str; if ($str === '') { return ''; } if ($clean_utf8) { // "mb_strpos()" and "iconv_strpos()" returns wrong position, // if invalid characters are found in $haystack before $needle $str = self::clean($str); } // hack for old php version or for the polyfill ... if ($try_to_keep_the_string_length) { $str = self::fixStrCaseHelper($str, true); } if ($lang === null && $encoding === 'UTF-8') { return \mb_strtolower($str); } $encoding = self::normalize_encoding($encoding, 'UTF-8'); if ($lang !== null) { if (self::$SUPPORT['intl'] === true) { if (self::$INTL_TRANSLITERATOR_LIST === null) { self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list'); } $language_code = $lang . '-Lower'; if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) { /** * @psalm-suppress ImpureFunctionCall - this is only a warning */ \trigger_error('UTF8::strtolower() cannot handle special language: ' . $lang . ' | supported: ' . \print_r(self::$INTL_TRANSLITERATOR_LIST, true), \E_USER_WARNING); $language_code = 'Any-Lower'; } return (string) \transliterator_transliterate($language_code, $str); } /** * @psalm-suppress ImpureFunctionCall - this is only a warning */ \trigger_error('UTF8::strtolower() without intl cannot handle the "lang" parameter: ' . $lang, \E_USER_WARNING); } // always fallback via symfony polyfill return \mb_strtolower($str, $encoding); } /** * Make a string uppercase. * * EXAMPLE:UTF8::strtoupper('Déjà Σσς Iıİi'); // 'DÉJÀ ΣΣΣ IIİI'
*
* @see http://php.net/manual/en/function.mb-strtoupper.php
*
* @param string $str The string being uppercased.
* @param string $encoding [optional]Set the charset.
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* @param string|null $lang [optional]Set the language for special cases: az, el, lt, * tr
* @param bool $try_to_keep_the_string_length [optional]true === try to keep the string length: e.g. ẞ * -> ß
* * @psalm-pure * * @return string *String with all alphabetic characters converted to uppercase.
*/ public static function strtoupper( $str, string $encoding = 'UTF-8', bool $clean_utf8 = false, ?string $lang = null, bool $try_to_keep_the_string_length = false ): string { // init $str = (string) $str; if ($str === '') { return ''; } if ($clean_utf8) { // "mb_strpos()" and "iconv_strpos()" returns wrong position, // if invalid characters are found in $haystack before $needle $str = self::clean($str); } // hack for old php version or for the polyfill ... if ($try_to_keep_the_string_length) { $str = self::fixStrCaseHelper($str); } if ($lang === null && $encoding === 'UTF-8') { return \mb_strtoupper($str); } $encoding = self::normalize_encoding($encoding, 'UTF-8'); if ($lang !== null) { if (self::$SUPPORT['intl'] === true) { if (self::$INTL_TRANSLITERATOR_LIST === null) { self::$INTL_TRANSLITERATOR_LIST = self::getData('transliterator_list'); } $language_code = $lang . '-Upper'; if (!\in_array($language_code, self::$INTL_TRANSLITERATOR_LIST, true)) { /** * @psalm-suppress ImpureFunctionCall - this is only a warning */ \trigger_error('UTF8::strtoupper() without intl for special language: ' . $lang, \E_USER_WARNING); $language_code = 'Any-Upper'; } return (string) \transliterator_transliterate($language_code, $str); } /** * @psalm-suppress ImpureFunctionCall - this is only a warning */ \trigger_error('UTF8::strtolower() without intl cannot handle the "lang"-parameter: ' . $lang, \E_USER_WARNING); } // always fallback via symfony polyfill return \mb_strtoupper($str, $encoding); } /** * Translate characters or replace sub-strings. * * EXAMPLE: *
* $array = [
* 'Hello' => '○●◎',
* '中文空白' => 'earth',
* ];
* UTF8::strtr('Hello 中文空白', $array); // '○●◎ earth'
*
*
* @see http://php.net/manual/en/function.strtr.php
*
* @param string $str The string being translated.
* @param string|string[] $fromThe string replacing from.
* @param string|string[] $to [optional]The string being translated to to.
* * @psalm-pure * * @return string *This function returns a copy of str, translating all occurrences of each character in "from" * to the corresponding character in "to".
*/ public static function strtr(string $str, $from, $to = ''): string { if ($str === '') { return ''; } if ($from === $to) { return $str; } if ($to !== '') { if (!\is_array($from)) { $from = self::str_split($from); } if (!\is_array($to)) { $to = self::str_split($to); } $count_from = \count($from); $count_to = \count($to); if ($count_from !== $count_to) { if ($count_from > $count_to) { $from = \array_slice($from, 0, $count_to); } elseif ($count_from < $count_to) { $to = \array_slice($to, 0, $count_from); } } try { $from = \array_combine($from, $to); } catch (\Error $e) { // PHP >= 8.0 : array_combine() will now throw a ValueError if the number of elements for each array is not equal; previously this function returned false instead. $from = false; } if ($from === false) { throw new \InvalidArgumentException('The number of elements for each array isn\'t equal or the arrays are empty: (from: ' . \print_r($from, true) . ' | to: ' . \print_r($to, true) . ')'); } } if (\is_string($from)) { return \str_replace($from, $to, $str); } return \strtr($str, $from); } /** * Return the width of a string. * * INFO: use UTF8::strlen() for the byte-length * * EXAMPLE:UTF8::strwidth("Iñtërnâtiôn\xE9àlizætiøn")); // 21
*
* @param string $str The input string.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return int * * @phpstan-return 0|positive-int */ public static function strwidth( string $str, string $encoding = 'UTF-8', bool $clean_utf8 = false ): int { if ($str === '') { return 0; } if ($encoding !== 'UTF-8' && $encoding !== 'CP850') { $encoding = self::normalize_encoding($encoding, 'UTF-8'); } if ($clean_utf8) { // iconv and mbstring are not tolerant to invalid encoding // further, their behaviour is inconsistent with that of PHP's substr $str = self::clean($str); } // // fallback via mbstring // if (self::$SUPPORT['mbstring'] === true) { if ($encoding === 'UTF-8') { return \mb_strwidth($str); } return \mb_strwidth($str, $encoding); } // // fallback via vanilla php // if ($encoding !== 'UTF-8') { $str = self::encode('UTF-8', $str, false, $encoding); } $wide = 0; $str = (string) \preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $str, -1, $wide); /* @phpstan-ignore-next-line | should return 0|positive-int */ return ($wide << 1) + (int) self::strlen($str); } /** * Get part of a string. * * EXAMPLE:UTF8::substr('中文空白', 1, 2); // '文空'
*
* @see http://php.net/manual/en/function.mb-substr.php
*
* @param string $str The string being checked.
* @param int $offsetThe first position used in str.
* @param int|null $length [optional]The maximum length of the returned string.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|string * The portion of str specified by the offset and * length parameters.If str is shorter than offset
* characters long, FALSE will be returned.
*/
public static function substr(
string $str,
int $offset = 0,
?int $length = null,
string $encoding = 'UTF-8',
bool $clean_utf8 = false
) {
// empty string
if ($str === '' || $length === 0) {
return '';
}
if ($clean_utf8) {
// iconv and mbstring are not tolerant to invalid encoding
// further, their behaviour is inconsistent with that of PHP's substr
$str = self::clean($str);
}
// whole string
if (!$offset && $length === null) {
return $str;
}
if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
$encoding = self::normalize_encoding($encoding, 'UTF-8');
}
//
// fallback via mbstring
//
if (self::$SUPPORT['mbstring'] === true && $encoding === 'UTF-8') {
if ($length === null) {
return \mb_substr($str, $offset);
}
return \mb_substr($str, $offset, $length);
}
//
// fallback for binary || ascii only
//
if (
$encoding === 'CP850'
||
$encoding === 'ASCII'
) {
if ($length === null) {
return \substr($str, $offset);
}
return \substr($str, $offset, $length);
}
// otherwise we need the string-length
$str_length = 0;
if (
$offset
||
$length === null /* @phpstan-ignore-line | can be NULL here?! */
) {
$str_length = self::strlen($str, $encoding);
}
// e.g.: invalid chars + mbstring not installed
if ($str_length === false) {
return false;
}
// empty string
if ($offset === $str_length && !$length) {
return '';
}
// impossible
if ($offset && $offset > $str_length) {
return '';
}
$length = $length ?? $str_length;
if (
$encoding !== 'UTF-8'
&&
self::$SUPPORT['mbstring'] === false
) {
/**
* @psalm-suppress ImpureFunctionCall - this is only a warning
*/
\trigger_error('UTF8::substr() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING);
}
//
// fallback via intl
//
if (
$encoding === 'UTF-8' // INFO: "grapheme_substr()" can't handle other encodings
&&
$offset >= 0 // grapheme_substr() can't handle negative offset
&&
self::$SUPPORT['intl'] === true
) {
$return_tmp = \grapheme_substr($str, $offset, $length);
if ($return_tmp !== false) {
return $return_tmp;
}
}
//
// fallback via iconv
//
if (
$length >= 0 // "iconv_substr()" can't handle negative length
&&
self::$SUPPORT['iconv'] === true
) {
$return_tmp = \iconv_substr($str, $offset, $length);
if ($return_tmp !== false) {
return $return_tmp;
}
}
//
// fallback for ascii only
//
if (ASCII::is_ascii($str)) {
return \substr($str, $offset, $length);
}
//
// fallback via vanilla php
//
// split to array, and remove invalid characters
// &&
// extract relevant part, and join to make sting again
return \implode('', \array_slice(self::str_split($str), $offset, $length));
}
/**
* Binary-safe comparison of two strings from an offset, up to a length of characters.
*
* EXAMPLE:
* UTF8::substr_compare("○●◎\r", '●◎', 0, 2); // -1
* UTF8::substr_compare("○●◎\r", '◎●', 1, 2); // 1
* UTF8::substr_compare("○●◎\r", '●◎', 1, 2); // 0
*
*
* @param string $str1
The main string being compared.
* @param string $str2The secondary string being compared.
* @param int $offset [optional]The start position for the comparison. If negative, it starts * counting from the end of the string.
* @param int|null $length [optional]The length of the comparison. The default value is the largest * of the length of the str compared to the length of main_str less the * offset.
* @param bool $case_insensitivity [optional]If case_insensitivity is TRUE, comparison is case * insensitive.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return int * < 0 if str1 is less than str2;UTF8::substr_count('中文空白', '文空', 1, 2); // 1
*
* @see http://php.net/manual/en/function.substr-count.php
*
* @param string $haystack The string to search in.
* @param string $needleThe substring to search for.
* @param int $offset [optional]The offset where to start counting.
* @param int|null $length [optional]* The maximum length after the specified offset to search for the * substring. It outputs a warning if the offset plus the length is * greater than the haystack length. *
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return false|int *This functions returns an integer or false if there isn't a string.
*/ public static function substr_count( string $haystack, string $needle, int $offset = 0, ?int $length = null, string $encoding = 'UTF-8', bool $clean_utf8 = false ) { if ($needle === '') { return false; } if ($haystack === '' || $length === 0) { return 0; } if ($encoding !== 'UTF-8' && $encoding !== 'CP850') { $encoding = self::normalize_encoding($encoding, 'UTF-8'); } if ($clean_utf8) { // "mb_strpos()" and "iconv_strpos()" returns wrong position, // if invalid characters are found in $haystack before $needle $needle = self::clean($needle); $haystack = self::clean($haystack); } if ($offset || $length > 0) { if ($length === null) { $length_tmp = self::strlen($haystack, $encoding); if ($length_tmp === false) { return false; } $length = $length_tmp; } if ($encoding === 'UTF-8') { $haystack = (string) \mb_substr($haystack, $offset, $length); } else { $haystack = (string) \mb_substr($haystack, $offset, $length, $encoding); } } if ( $encoding !== 'UTF-8' && self::$SUPPORT['mbstring'] === false ) { /** * @psalm-suppress ImpureFunctionCall - this is only a warning */ \trigger_error('UTF8::substr_count() without mbstring cannot handle "' . $encoding . '" encoding', \E_USER_WARNING); } if (self::$SUPPORT['mbstring'] === true) { if ($encoding === 'UTF-8') { return \mb_substr_count($haystack, $needle); } return \mb_substr_count($haystack, $needle, $encoding); } \preg_match_all('/' . \preg_quote($needle, '/') . '/us', $haystack, $matches, \PREG_SET_ORDER); return \count($matches); } /** * Count the number of substring occurrences. * * @param string $haystack* The string being checked. *
* @param string $needle* The string being found. *
* @param int $offset [optional]* The offset where to start counting *
* @param int|null $length [optional]* The maximum length after the specified offset to search for the * substring. It outputs a warning if the offset plus the length is * greater than the haystack length. *
* * @psalm-pure * * @return false|int *The number of times the * needle substring occurs in the * haystack string.
*/ public static function substr_count_in_byte( string $haystack, string $needle, int $offset = 0, ?int $length = null ) { if ($haystack === '' || $needle === '') { return 0; } if ( ($offset || $length !== null) && self::$SUPPORT['mbstring_func_overload'] === true ) { if ($length === null) { $length_tmp = self::strlen($haystack); if ($length_tmp === false) { return false; } $length = $length_tmp; } if ( ( $length !== 0 && $offset !== 0 ) && ($length + $offset) <= 0 && \PHP_VERSION_ID < 71000 // output from "substr_count()" have changed in PHP 7.1 ) { return false; } /** @var false|string $haystack_tmp - needed for PhpStan (stubs error) */ $haystack_tmp = \substr($haystack, $offset, $length); if ($haystack_tmp === false) { $haystack_tmp = ''; } $haystack = (string) $haystack_tmp; } if (self::$SUPPORT['mbstring_func_overload'] === true) { // "mb_" is available if overload is used, so use it ... return \mb_substr_count($haystack, $needle, 'CP850'); // 8-BIT } if ($length === null) { return \substr_count($haystack, $needle, $offset); } return \substr_count($haystack, $needle, $offset, $length); } /** * Returns the number of occurrences of $substring in the given string. * By default, the comparison is case-sensitive, but can be made insensitive * by setting $case_sensitive to false. * * @param string $strThe input string.
* @param string $substringThe substring to search for.
* @param bool $case_sensitive [optional]Whether or not to enforce case-sensitivity. Default: true
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return int * * @phpstan-return 0|positive-int */ public static function substr_count_simple( string $str, string $substring, bool $case_sensitive = true, string $encoding = 'UTF-8' ): int { if ($str === '' || $substring === '') { return 0; } if ($encoding === 'UTF-8') { if ($case_sensitive) { return (int) \mb_substr_count($str, $substring); } return (int) \mb_substr_count( \mb_strtoupper($str), \mb_strtoupper($substring) ); } $encoding = self::normalize_encoding($encoding, 'UTF-8'); if ($case_sensitive) { return (int) \mb_substr_count($str, $substring, $encoding); } return (int) \mb_substr_count( self::strtocasefold($str, true, false, $encoding, null, false), self::strtocasefold($substring, true, false, $encoding, null, false), $encoding ); } /** * Removes a prefix ($needle) from the beginning of the string ($haystack), case-insensitive. * * EXMAPLE:
* UTF8::substr_ileft('ΚόσμεMiddleEnd', 'Κόσμε'); // 'MiddleEnd'
* UTF8::substr_ileft('ΚόσμεMiddleEnd', 'κόσμε'); // 'MiddleEnd'
*
*
* @param string $haystack The string to search in.
* @param string $needleThe substring to search for.
* * @psalm-pure * * @return string *Return the sub-string.
*/ public static function substr_ileft(string $haystack, string $needle): string { if ($haystack === '') { return ''; } if ($needle === '') { return $haystack; } if (self::str_istarts_with($haystack, $needle)) { $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle)); } return $haystack; } /** * Get part of a string process in bytes. * * @param string $strThe string being checked.
* @param int $offsetThe first position used in str.
* @param int|null $length [optional]The maximum length of the returned string.
* * @psalm-pure * * @return false|string *The portion of str specified by the offset and * length parameters.
If str is shorter than offset * characters long, FALSE will be returned.
*/ public static function substr_in_byte(string $str, int $offset = 0, ?int $length = null) { // empty string if ($str === '' || $length === 0) { return ''; } // whole string if (!$offset && $length === null) { return $str; } if (self::$SUPPORT['mbstring_func_overload'] === true) { // "mb_" is available if overload is used, so use it ... return \mb_substr($str, $offset, $length, 'CP850'); // 8-BIT } return \substr($str, $offset, $length ?? 2147483647); } /** * Removes a suffix ($needle) from the end of the string ($haystack), case-insensitive. * * EXAMPLE:
* UTF8::substr_iright('BeginMiddleΚόσμε', 'Κόσμε'); // 'BeginMiddle'
* UTF8::substr_iright('BeginMiddleΚόσμε', 'κόσμε'); // 'BeginMiddle'
*
*
* @param string $haystack The string to search in.
* @param string $needleThe substring to search for.
* * @psalm-pure * * @return string *Return the sub-string.
*/
public static function substr_iright(string $haystack, string $needle): string
{
if ($haystack === '') {
return '';
}
if ($needle === '') {
return $haystack;
}
if (self::str_iends_with($haystack, $needle)) {
$haystack = (string) \mb_substr($haystack, 0, (int) self::strlen($haystack) - (int) self::strlen($needle));
}
return $haystack;
}
/**
* Removes a prefix ($needle) from the beginning of the string ($haystack).
*
* EXAMPLE:
* UTF8::substr_left('ΚόσμεMiddleEnd', 'Κόσμε'); // 'MiddleEnd'
* UTF8::substr_left('ΚόσμεMiddleEnd', 'κόσμε'); // 'ΚόσμεMiddleEnd'
*
*
* @param string $haystack
The string to search in.
* @param string $needleThe substring to search for.
* * @psalm-pure * * @return string *Return the sub-string.
*/ public static function substr_left(string $haystack, string $needle): string { if ($haystack === '') { return ''; } if ($needle === '') { return $haystack; } if (self::str_starts_with($haystack, $needle)) { $haystack = (string) \mb_substr($haystack, (int) self::strlen($needle)); } return $haystack; } /** * Replace text within a portion of a string. * * EXAMPLE:UTF8::substr_replace(array('Iñtërnâtiônàlizætiøn', 'foo'), 'æ', 1); // array('Iæñtërnâtiônàlizætiøn', 'fæoo')
*
* source: https://gist.github.com/stemar/8287074
*
* @param string|string[] $str The input string or an array of stings.
* @param string|string[] $replacementThe replacement string or an array of stings.
* @param int|int[] $offset
* If start is positive, the replacing will begin at the start'th offset
* into string.
*
* If start is negative, the replacing will begin at the start'th character
* from the end of string.
*
If given and is positive, it represents the length of the * portion of string which is to be replaced. If it is negative, it * represents the number of characters from the end of string at which to * stop replacing. If it is not given, then it will default to strlen( * string ); i.e. end the replacing at the end of string. Of course, if * length is zero then this function will have the effect of inserting * replacement into string at the given start offset.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return string|string[] *The result string is returned. If string is an array then array is returned.
* * @template TSubstrReplace string|string[] * @phpstan-param TSubstrReplace $str * @phpstan-return TSubstrReplace */ public static function substr_replace( $str, $replacement, $offset, $length = null, string $encoding = 'UTF-8' ) { if (\is_array($str)) { $num = \count($str); // the replacement if (\is_array($replacement)) { $replacement = \array_slice($replacement, 0, $num); } else { $replacement = \array_pad([$replacement], $num, $replacement); } // the offset if (\is_array($offset)) { $offset = \array_slice($offset, 0, $num); foreach ($offset as &$value_tmp) { $value_tmp = (int) $value_tmp === $value_tmp ? $value_tmp : 0; } unset($value_tmp); } else { $offset = \array_pad([$offset], $num, $offset); } // the length if ($length === null) { $length = \array_fill(0, $num, 0); } elseif (\is_array($length)) { $length = \array_slice($length, 0, $num); foreach ($length as &$value_tmp_V2) { $value_tmp_V2 = (int) $value_tmp_V2 === $value_tmp_V2 ? $value_tmp_V2 : $num; } unset($value_tmp_V2); } else { $length = \array_pad([$length], $num, $length); } // recursive call /** @phpstan-ignore-next-line - phpstan currently can't handle recursive calls */ return \array_map([self::class, 'substr_replace'], $str, $replacement, $offset, $length); } if (\is_array($replacement)) { if ($replacement !== []) { $replacement = $replacement[0]; } else { $replacement = ''; } } // init $str = (string) $str; $replacement = (string) $replacement; if (\is_array($length)) { throw new \InvalidArgumentException('Parameter "$length" can only be an array, if "$str" is also an array.'); } if (\is_array($offset)) { throw new \InvalidArgumentException('Parameter "$offset" can only be an array, if "$str" is also an array.'); } if ($str === '') { return $replacement; } if (self::$SUPPORT['mbstring'] === true) { $string_length = (int) self::strlen($str, $encoding); if ($offset < 0) { $offset = (int) \max(0, $string_length + $offset); } elseif ($offset > $string_length) { $offset = $string_length; } if ($length !== null && $length < 0) { $length = (int) \max(0, $string_length - $offset + $length); } elseif ($length === null || $length > $string_length) { $length = $string_length; } if (($offset + $length) > $string_length) { $length = $string_length - $offset; } return ((string) \mb_substr($str, 0, $offset, $encoding)) . $replacement . ((string) \mb_substr($str, $offset + $length, $string_length - $offset - $length, $encoding)); } // // fallback for ascii only // if (ASCII::is_ascii($str)) { return ($length === null) ? \substr_replace($str, $replacement, $offset) : \substr_replace($str, $replacement, $offset, $length); } // // fallback via vanilla php // \preg_match_all('/./us', $str, $str_matches); \preg_match_all('/./us', $replacement, $replacement_matches); if ($length === null) { $length_tmp = self::strlen($str, $encoding); if ($length_tmp === false) { // e.g.: non mbstring support + invalid chars return ''; } $length = $length_tmp; } \array_splice($str_matches[0], $offset, $length, $replacement_matches[0]); return \implode('', $str_matches[0]); } /** * Removes a suffix ($needle) from the end of the string ($haystack). * * EXAMPLE:
* UTF8::substr_right('BeginMiddleΚόσμε', 'Κόσμε'); // 'BeginMiddle'
* UTF8::substr_right('BeginMiddleΚόσμε', 'κόσμε'); // 'BeginMiddleΚόσμε'
*
*
* @param string $haystack The string to search in.
* @param string $needleThe substring to search for.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* * @psalm-pure * * @return string *Return the sub-string.
*/ public static function substr_right( string $haystack, string $needle, string $encoding = 'UTF-8' ): string { if ($haystack === '') { return ''; } if ($needle === '') { return $haystack; } if ( $encoding === 'UTF-8' && \substr($haystack, -\strlen($needle)) === $needle ) { return (string) \mb_substr($haystack, 0, (int) \mb_strlen($haystack) - (int) \mb_strlen($needle)); } if (\substr($haystack, -\strlen($needle)) === $needle) { return (string) self::substr( $haystack, 0, (int) self::strlen($haystack, $encoding) - (int) self::strlen($needle, $encoding), $encoding ); } return $haystack; } /** * Returns a case swapped version of the string. * * EXAMPLE:UTF8::swapCase('déJÀ σσς iıII'); // 'DÉjà ΣΣΣ IIii'
*
* @param string $str The input string.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* * @psalm-pure * * @return string *Each character's case swapped.
*/ public static function swapCase(string $str, string $encoding = 'UTF-8', bool $clean_utf8 = false): string { if ($str === '') { return ''; } if ($clean_utf8) { // "mb_strpos()" and "iconv_strpos()" returns wrong position, // if invalid characters are found in $haystack before $needle $str = self::clean($str); } if ($encoding === 'UTF-8') { return (string) (\mb_strtolower($str) ^ \mb_strtoupper($str) ^ $str); } return (string) (self::strtolower($str, $encoding) ^ self::strtoupper($str, $encoding) ^ $str); } /** * Checks whether symfony-polyfills are used. * * @psalm-pure * * @return bool *true if in use, false otherwise
* * @internalPlease do not use it anymore, we will make is private in next major version.
*/ public static function symfony_polyfill_used(): bool { // init $return = false; $return_tmp = \extension_loaded('mbstring'); if (!$return_tmp && \function_exists('mb_strlen')) { $return = true; } $return_tmp = \extension_loaded('iconv'); if (!$return_tmp && \function_exists('iconv')) { $return = true; } return $return; } /** * @param string $str * @param int $tab_length * * @psalm-pure * * @return string */ public static function tabs_to_spaces(string $str, int $tab_length = 4): string { if ($tab_length === 4) { $spaces = ' '; } elseif ($tab_length === 2) { $spaces = ' '; } else { $spaces = \str_repeat(' ', $tab_length); } return \str_replace("\t", $spaces, $str); } /** * Converts the first character of each word in the string to uppercase * and all other chars to lowercase. * * @param string $strThe input string.
* @param string $encoding [optional]Set the charset for e.g. "mb_" function
* @param bool $clean_utf8 [optional]Remove non UTF-8 chars from the string.
* @param string|null $lang [optional]Set the language for special cases: az, el, lt, * tr
* @param bool $try_to_keep_the_string_length [optional]true === try to keep the string length: e.g. ẞ * -> ß
* * @p