0 follower

Final Class Yiisoft\Strings\StringHelper

InheritanceYiisoft\Strings\StringHelper

Provides static methods to work with strings.

Public Methods

Hide inherited methods

Method Description Defined By
base64UrlDecode() Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648). Yiisoft\Strings\StringHelper
base64UrlEncode() Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648). Yiisoft\Strings\StringHelper
baseName() Returns the trailing name component of a path. Yiisoft\Strings\StringHelper
byteLength() Returns the number of bytes in the given string. Yiisoft\Strings\StringHelper
byteSubstring() Returns the portion of string specified by the start and length parameters. Yiisoft\Strings\StringHelper
countWords() Counts words in a string. Yiisoft\Strings\StringHelper
directoryName() Returns parent directory's path. Yiisoft\Strings\StringHelper
endsWith() Check if given string ends with specified substring. Yiisoft\Strings\StringHelper
endsWithIgnoringCase() Check if given string ends with specified substring. Yiisoft\Strings\StringHelper
findBetween() Returns the portion of the string that lies between the first occurrence of the $start string and the last occurrence of the $end string after that. Yiisoft\Strings\StringHelper
findBetweenFirst() Returns the portion of the string between the initial occurrence of the '$start' string and the next occurrence of the '$end' string. Yiisoft\Strings\StringHelper
findBetweenLast() Returns the portion of the string between the latest '$start' string and the subsequent '$end' string. Yiisoft\Strings\StringHelper
length() Get string length. Yiisoft\Strings\StringHelper
lowercase() Make a string lowercase. Yiisoft\Strings\StringHelper
ltrim() Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning of a string. Yiisoft\Strings\StringHelper
matchAnyRegex() Checks if a given string matches any of the provided patterns. Yiisoft\Strings\StringHelper
parsePath() Yiisoft\Strings\StringHelper
replaceSubstring() Replace text within a portion of a string. Yiisoft\Strings\StringHelper
rtrim() Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the end of a string. Yiisoft\Strings\StringHelper
split() Split a string to array with non-empty lines. Yiisoft\Strings\StringHelper
startsWith() Check if given string starts with specified substring. Yiisoft\Strings\StringHelper
startsWithIgnoringCase() Check if given string starts with specified substring ignoring case. Yiisoft\Strings\StringHelper
substring() Get part of string. Yiisoft\Strings\StringHelper
trim() Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning and end of a string. Yiisoft\Strings\StringHelper
truncateBegin() Truncates a string from the beginning to the number of characters specified. Yiisoft\Strings\StringHelper
truncateEnd() Truncates a string from the end to the number of characters specified. Yiisoft\Strings\StringHelper
truncateMiddle() Truncates a string in the middle. Keeping start and end. Yiisoft\Strings\StringHelper
truncateWords() Truncates a string to the number of words specified. Yiisoft\Strings\StringHelper
truncateWordsByLength() Truncates a string to the specified character length while preserving word boundaries. Yiisoft\Strings\StringHelper
uppercase() Make a string uppercase. Yiisoft\Strings\StringHelper
uppercaseFirstCharacter() Make a string's first character uppercase. Yiisoft\Strings\StringHelper
uppercaseFirstCharacterInEachWord() Uppercase the first character of each word in a string. Yiisoft\Strings\StringHelper

Constants

Hide inherited constants

Constant Value Description Defined By
DEFAULT_WHITESPACE_PATTERN "\\pC\\pZ" Yiisoft\Strings\StringHelper

Method Details

Hide inherited methods

base64UrlDecode() public static method

Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).

See also https://tools.ietf.org/html/rfc4648#page-7.

public static string base64UrlDecode ( string $input )
$input string

Encoded string.

return string

Decoded string.

                public static function base64UrlDecode(string $input): string
{
    return base64_decode(strtr($input, '-_', '+/'));
}

            
base64UrlEncode() public static method

Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).

Note: Base 64 padding = may be at the end of the returned string. = is not transparent to URL encoding.

See also https://tools.ietf.org/html/rfc4648#page-7.

public static string base64UrlEncode ( string $input )
$input string

The string to encode.

return string

Encoded string.

                public static function base64UrlEncode(string $input): string
{
    return strtr(base64_encode($input), '+/', '-_');
}

            
baseName() public static method

Returns the trailing name component of a path.

This method is similar to the php function basename() except that it will treat both \ and / as directory separators, independent of the operating system. This method was mainly created to work on php namespaces. When working with real file paths, PHP's basename() should work fine for you. Note: this method is not aware of the actual filesystem, or path components such as "..".

See also https://www.php.net/manual/en/function.basename.php.

public static string baseName ( string $path, string $suffix '' )
$path string

A path string.

$suffix string

If the name component ends in suffix this will also be cut off.

return string

The trailing name component of the given path.

                public static function baseName(string $path, string $suffix = ''): string
{
    $length = mb_strlen($suffix);
    if ($length > 0 && mb_substr($path, -$length) === $suffix) {
        $path = mb_substr($path, 0, -$length);
    }
    $path = rtrim(str_replace('\\', '/', $path), '/\\');
    $position = mb_strrpos($path, '/');
    if ($position !== false) {
        return mb_substr($path, $position + 1);
    }
    return $path;
}

            
byteLength() public static method

Returns the number of bytes in the given string.

This method ensures the string is treated as a byte array even if mbstring.func_overload is turned on by using {@see \Yiisoft\Strings\mb_strlen()}.

public static integer byteLength ( string|null $input )
$input string|null

The string being measured for length.

return integer

The number of bytes in the given string.

                public static function byteLength(string|null $input): int
{
    return mb_strlen((string)$input, '8bit');
}

            
byteSubstring() public static method

Returns the portion of string specified by the start and length parameters.

This method ensures the string is treated as a byte array by using mb_substr().

See also https://www.php.net/manual/en/function.substr.php.

public static string byteSubstring ( string $input, integer $start, integer|null $length null )
$input string

The input string. Must be one character or longer.

$start integer

The starting position.

$length integer|null

The desired portion length. If not specified or null, there will be no limit on length i.e. the output will be until the end of the string.

return string

The extracted part of string, or FALSE on failure or an empty string.

                public static function byteSubstring(string $input, int $start, ?int $length = null): string
{
    return mb_substr($input, $start, $length ?? mb_strlen($input, '8bit'), '8bit');
}

            
countWords() public static method

Counts words in a string.

public static integer countWords ( string $input )
$input string

                public static function countWords(string $input): int
{
    /** @var array $words */
    $words = preg_split('/\s+/u', $input, -1, PREG_SPLIT_NO_EMPTY);
    return count($words);
}

            
directoryName() public static method

Returns parent directory's path.

This method is similar to dirname() except that it will treat both \ and / as directory separators, independent of the operating system.

See also https://www.php.net/manual/en/function.basename.php.

public static string directoryName ( string $path )
$path string

A path string.

return string

The parent directory's path.

                public static function directoryName(string $path): string
{
    $position = mb_strrpos(str_replace('\\', '/', $path), '/');
    if ($position !== false) {
        return mb_substr($path, 0, $position);
    }
    return '';
}

            
endsWith() public static method

Check if given string ends with specified substring.

Binary and multibyte safe.

public static boolean endsWith ( string $input, string|null $with )
$input string

Input string to check.

$with string|null

Part to search inside the $string.

return boolean

Returns true if first input ends with second input, false otherwise.

                public static function endsWith(string $input, string|null $with): bool
{
    return $with === null || str_ends_with($input, $with);
}

            
endsWithIgnoringCase() public static method

Check if given string ends with specified substring.

Binary and multibyte safe.

public static boolean endsWithIgnoringCase ( string $input, string|null $with )
$input string

Input string to check.

$with string|null

Part to search inside the $string.

return boolean

Returns true if first input ends with second input, false otherwise.

                public static function endsWithIgnoringCase(string $input, string|null $with): bool
{
    $bytes = self::byteLength($with);
    if ($bytes === 0) {
        return true;
    }
    /** @psalm-suppress PossiblyNullArgument */
    return self::lowercase(mb_substr($input, -$bytes, mb_strlen($input, '8bit'), '8bit')) === self::lowercase($with);
}

            
findBetween() public static method

Returns the portion of the string that lies between the first occurrence of the $start string and the last occurrence of the $end string after that.

public static string|null findBetween ( string $string, string $start, string|null $end null )
$string string

The input string.

$start string

The string marking the start of the portion to extract.

$end string|null

The string marking the end of the portion to extract. If the $end string is not provided, it defaults to the value of the $start string.

return string|null

The portion of the string between the first occurrence of $start and the last occurrence of $end, or null if either $start or $end cannot be found.

                public static function findBetween(string $string, string $start, ?string $end = null): ?string
{
    if ($end === null) {
        $end = $start;
    }
    $startPos = mb_strpos($string, $start);
    if ($startPos === false) {
        return null;
    }
    $startPos += mb_strlen($start);
    $endPos = mb_strrpos($string, $end, $startPos);
    if ($endPos === false) {
        return null;
    }
    return mb_substr($string, $startPos, $endPos - $startPos);
}

            
findBetweenFirst() public static method

Returns the portion of the string between the initial occurrence of the '$start' string and the next occurrence of the '$end' string.

public static string|null findBetweenFirst ( string $string, string $start, string|null $end null )
$string string

The input string.

$start string

The string marking the beginning of the segment to extract.

$end string|null

The string marking the termination of the segment. If the '$end' string is not provided, it defaults to the value of the '$start' string.

return string|null

Extracted segment, or null if '$start' or '$end' is not present.

                public static function findBetweenFirst(string $string, string $start, ?string $end = null): ?string
{
    if ($end === null) {
        $end = $start;
    }
    $startPos = mb_strpos($string, $start);
    if ($startPos === false) {
        return null;
    }
    $startPos += mb_strlen($start);
    $endPos = mb_strpos($string, $end, $startPos);
    if ($endPos === false) {
        return null;
    }
    return mb_substr($string, $startPos, $endPos - $startPos);
}

            
findBetweenLast() public static method

Returns the portion of the string between the latest '$start' string and the subsequent '$end' string.

public static string|null findBetweenLast ( string $string, string $start, string|null $end null )
$string string

The input string.

$start string

The string marking the beginning of the segment to extract.

$end string|null

The string marking the termination of the segment. If the '$end' string is not provided, it defaults to the value of the '$start' string.

return string|null

Extracted segment, or null if '$start' or '$end' is not present.

                public static function findBetweenLast(string $string, string $start, ?string $end = null): ?string
{
    if ($end === null) {
        $end = $start;
    }
    $endPos = mb_strrpos($string, $end);
    if ($endPos === false) {
        return null;
    }
    $startPos = mb_strrpos(mb_substr($string, 0, $endPos), $start);
    if ($startPos === false) {
        return null;
    }
    $startPos += mb_strlen($start);
    return mb_substr($string, $startPos, $endPos - $startPos);
}

            
length() public static method
public static integer length ( string $string, string $encoding 'UTF-8' )
$string string

String to calculate length for.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function length(string $string, string $encoding = 'UTF-8'): int
{
    return mb_strlen($string, $encoding);
}

            
lowercase() public static method

Make a string lowercase.

See also https://php.net/manual/en/function.mb-strtolower.php.

public static string lowercase ( string $string, string $encoding 'UTF-8' )
$string string

String to process.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function lowercase(string $string, string $encoding = 'UTF-8'): string
{
    return mb_strtolower($string, $encoding);
}

            
ltrim() public static method

Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning of a string.

See also \Yiisoft\Strings\self::trim().

public static string|string[] ltrim ( string|string[] $string, string $pattern self::DEFAULT_WHITESPACE_PATTERN )
$string string|string[]

The string or an array with strings.

$pattern string

PCRE regex pattern to search for, as UTF-8 string. Use {@see \Yiisoft\Strings\preg_quote()} to quote $pattern if it contains special regular expression characters.

                public static function ltrim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
{
    self::ensureUtf8String($string);
    self::ensureUtf8Pattern($pattern);
    /**
     * @var string|string[] `$string` is correct UTF-8 string and `$pattern` is correct (it should be passed
     * already prepared), so `preg_replace` never returns `null`.
     */
    return preg_replace("#^[$pattern]+#u", '', $string);
}

            
matchAnyRegex() public static method

Checks if a given string matches any of the provided patterns.

Note that patterns should be provided without delimiters on both sides. For example, te(s|x)t.

See also:

public static boolean matchAnyRegex ( string $string, string[] $patterns, string $flags '' )
$string string

The string to match against the patterns.

$patterns string[]

Regular expressions without delimiters on both sides.

$flags string

Flags to apply to all regular expressions.

                public static function matchAnyRegex(string $string, array $patterns, string $flags = ''): bool
{
    if (empty($patterns)) {
        return false;
    }
    return (new CombinedRegexp($patterns, $flags))->matches($string);
}

            
parsePath() public static method

public static string[] parsePath ( string $path, string $delimiter '.', string $escapeCharacter '\\', boolean $preserveDelimiterEscaping false )
$path string

The path of where do you want to write a value to $array. The path can be described by a string when each key should be separated by delimiter. If a path item contains delimiter, it can be escaped with "\" (backslash) or a custom delimiter can be used.

$delimiter string

A separator, used to parse string key for embedded object property retrieving. Defaults to "." (dot).

$escapeCharacter string

An escape character, used to escape delimiter. Defaults to "\" (backslash).

$preserveDelimiterEscaping boolean

Whether to preserve delimiter escaping in the items of final array (in case of using string as an input). When false, "\" (backslashes) are removed. For a "." as delimiter, "." becomes ".". Defaults to false.

                public static function parsePath(
    string $path,
    string $delimiter = '.',
    string $escapeCharacter = '\\',
    bool $preserveDelimiterEscaping = false
): array {
    if (strlen($delimiter) !== 1) {
        throw new InvalidArgumentException('Only 1 character is allowed for delimiter.');
    }
    if (strlen($escapeCharacter) !== 1) {
        throw new InvalidArgumentException('Only 1 escape character is allowed.');
    }
    if ($delimiter === $escapeCharacter) {
        throw new InvalidArgumentException('Delimiter and escape character must be different.');
    }
    if ($path === '') {
        return [''];
    }
    if (!str_contains($path, $delimiter)) {
        if ($preserveDelimiterEscaping) {
            return [$path];
        }
        return [str_replace($escapeCharacter . $escapeCharacter, $escapeCharacter, $path)];
    }
    /** @psalm-var non-empty-list<array{0:string, 1:int}> $matches */
    $matches = preg_split(
        sprintf(
            '/(?<!%1$s)((?>%1$s%1$s)*)%2$s/',
            preg_quote($escapeCharacter, '/'),
            preg_quote($delimiter, '/')
        ),
        $path,
        -1,
        PREG_SPLIT_OFFSET_CAPTURE
    );
    $result = [];
    $countResults = count($matches);
    for ($i = 1; $i < $countResults; $i++) {
        $l = $matches[$i][1] - $matches[$i - 1][1] - strlen($matches[$i - 1][0]) - 1;
        $result[] = $matches[$i - 1][0] . ($l > 0 ? str_repeat($escapeCharacter, $l) : '');
    }
    $result[] = $matches[$countResults - 1][0];
    if ($preserveDelimiterEscaping === true) {
        return $result;
    }
    return array_map(
        static fn (string $key): string => str_replace(
            [
                $escapeCharacter . $escapeCharacter,
                $escapeCharacter . $delimiter,
            ],
            [
                $escapeCharacter,
                $delimiter,
            ],
            $key
        ),
        $result
    );
}

            
replaceSubstring() public static method

Replace text within a portion of a string.

public static string replaceSubstring ( string $string, string $replacement, integer $start, integer|null $length null, string $encoding 'UTF-8' )
$string string

The input string.

$replacement string

The replacement string.

$start integer

Position to begin replacing substring at. If start is non-negative, 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.

$length integer|null

Length of the substring to be replaced. 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 the length of the string; i.e. end the replacing at the end of string. If length is zero then this function will have the effect of inserting replacement into string at the given start offset.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function replaceSubstring(
    string $string,
    string $replacement,
    int $start,
    int|null $length = null,
    string $encoding = 'UTF-8',
): string {
    $stringLength = mb_strlen($string, $encoding);
    if ($start < 0) {
        $start = max(0, $stringLength + $start);
    } elseif ($start > $stringLength) {
        $start = $stringLength;
    }
    if ($length !== null && $length < 0) {
        $length = max(0, $stringLength - $start + $length);
    } elseif ($length === null || $length > $stringLength) {
        $length = $stringLength;
    }
    if (($start + $length) > $stringLength) {
        $length = $stringLength - $start;
    }
    return mb_substr($string, 0, $start, $encoding)
        . $replacement
        . mb_substr($string, $start + $length, $stringLength - $start - $length, $encoding);
}

            
rtrim() public static method

Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the end of a string.

See also \Yiisoft\Strings\self::trim().

public static string|string[] rtrim ( string|string[] $string, string $pattern self::DEFAULT_WHITESPACE_PATTERN )
$string string|string[]

The string or an array with strings.

$pattern string

PCRE regex pattern to search for, as UTF-8 string. Use {@see \Yiisoft\Strings\preg_quote()} to quote $pattern if it contains special regular expression characters.

                public static function rtrim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
{
    self::ensureUtf8String($string);
    self::ensureUtf8Pattern($pattern);
    /**
     * @var string|string[] `$string` is correct UTF-8 string and `$pattern` is correct (it should be passed
     * already prepared), so `preg_replace` never returns `null`.
     */
    return preg_replace("#[$pattern]+$#uD", '', $string);
}

            
split() public static method

Split a string to array with non-empty lines.

Whitespace from the beginning and end of each line will be stripped.

public static array split ( string $string, string $separator '\\R' )
$string string

The input string. It must be valid UTF-8 string.

$separator string

The boundary string. It is a part of regular expression so should be taken into account or properly escaped with {@see \Yiisoft\Strings\preg_quote()}. It must be valid UTF-8 string.

                public static function split(string $string, string $separator = '\R'): array
{
    /**
     * @var string $string We assume that `$string` is valid UTF-8 string, so `preg_replace()` never returns
     * `false`.
     */
    $string = preg_replace('(^\s*|\s*$)', '', $string);
    /**
     * @var array We assume that $separator is prepared by `preg_quote()` and $string is valid UTF-8 string,
     * so `preg_split()` never returns `false`.
     */
    return preg_split('~\s*' . $separator . '\s*~u', $string, -1, PREG_SPLIT_NO_EMPTY);
}

            
startsWith() public static method

Check if given string starts with specified substring.

Binary and multibyte safe.

public static boolean startsWith ( string $input, string|null $with )
$input string

Input string.

$with string|null

Part to search inside the $string.

return boolean

Returns true if first input starts with second input, false otherwise.

                public static function startsWith(string $input, string|null $with): bool
{
    return $with === null || str_starts_with($input, $with);
}

            
startsWithIgnoringCase() public static method

Check if given string starts with specified substring ignoring case.

Binary and multibyte safe.

public static boolean startsWithIgnoringCase ( string $input, string|null $with )
$input string

Input string.

$with string|null

Part to search inside the $string.

return boolean

Returns true if first input starts with second input, false otherwise.

                public static function startsWithIgnoringCase(string $input, string|null $with): bool
{
    $bytes = self::byteLength($with);
    if ($bytes === 0) {
        return true;
    }
    /** @psalm-suppress PossiblyNullArgument */
    return self::lowercase(self::substring($input, 0, $bytes, '8bit')) === self::lowercase($with);
}

            
substring() public static method

Get part of string.

See also https://php.net/manual/en/function.mb-substr.php.

public static string substring ( string $string, integer $start, integer|null $length null, string $encoding 'UTF-8' )
$string string

To get substring from.

$start integer

Character to start at.

$length integer|null

Number of characters to get.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function substring(string $string, int $start, ?int $length = null, string $encoding = 'UTF-8'): string
{
    return mb_substr($string, $start, $length, $encoding);
}

            
trim() public static method

Strip Unicode whitespace (with Unicode symbol property White_Space=yes) or other characters from the beginning and end of a string.

Input string and pattern are treated as UTF-8.

See also:

public static string|string[] trim ( string|string[] $string, string $pattern self::DEFAULT_WHITESPACE_PATTERN )
$string string|string[]

The string or an array with strings.

$pattern string

PCRE regex pattern to search for, as UTF-8 string. Use {@see \Yiisoft\Strings\preg_quote()} to quote $pattern if it contains special regular expression characters.

                public static function trim(string|array $string, string $pattern = self::DEFAULT_WHITESPACE_PATTERN): string|array
{
    self::ensureUtf8String($string);
    self::ensureUtf8Pattern($pattern);
    /**
     * @var string|string[] `$string` is correct UTF-8 string and `$pattern` is correct (it should be passed
     * already prepared), so `preg_replace` never returns `null`.
     */
    return preg_replace("#^[$pattern]+|[$pattern]+$#uD", '', $string);
}

            
truncateBegin() public static method

Truncates a string from the beginning to the number of characters specified.

public static string truncateBegin ( string $input, integer $length, string $trimMarker '…', string $encoding 'UTF-8' )
$input string

String to process.

$length integer

Maximum length of the truncated string including trim marker.

$trimMarker string

String to append to the beginning.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function truncateBegin(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
{
    $inputLength = mb_strlen($input, $encoding);
    if ($inputLength <= $length) {
        return $input;
    }
    $trimMarkerLength = mb_strlen($trimMarker, $encoding);
    return self::replaceSubstring($input, $trimMarker, 0, -$length + $trimMarkerLength, $encoding);
}

            
truncateEnd() public static method

Truncates a string from the end to the number of characters specified.

public static string truncateEnd ( string $input, integer $length, string $trimMarker '…', string $encoding 'UTF-8' )
$input string

The string to truncate.

$length integer

Maximum length of the truncated string including trim marker.

$trimMarker string

String to append to the end of truncated string.

$encoding string

The encoding to use, defaults to "UTF-8".

return string

The truncated string.

                public static function truncateEnd(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
{
    $inputLength = mb_strlen($input, $encoding);
    if ($inputLength <= $length) {
        return $input;
    }
    $trimMarkerLength = mb_strlen($trimMarker, $encoding);
    return rtrim(mb_substr($input, 0, $length - $trimMarkerLength, $encoding)) . $trimMarker;
}

            
truncateMiddle() public static method

Truncates a string in the middle. Keeping start and end.

StringHelper::truncateMiddle('Hello world number 2', 8) produces "Hell…r 2".

public static string truncateMiddle ( string $input, integer $length, string $trimMarker '…', string $encoding 'UTF-8' )
$input string

The string to truncate.

$length integer

Maximum length of the truncated string including trim marker.

$trimMarker string

String to append in the middle of truncated string.

$encoding string

The encoding to use, defaults to "UTF-8".

return string

The truncated string.

                public static function truncateMiddle(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
{
    $inputLength = mb_strlen($input, $encoding);
    if ($inputLength <= $length) {
        return $input;
    }
    $trimMarkerLength = mb_strlen($trimMarker, $encoding);
    $start = (int)ceil(($length - $trimMarkerLength) / 2);
    $end = $length - $start - $trimMarkerLength;
    return self::replaceSubstring($input, $trimMarker, $start, -$end, $encoding);
}

            
truncateWords() public static method

Truncates a string to the number of words specified.

public static string truncateWords ( string $input, integer $count, string $trimMarker '…' )
$input string

The string to truncate.

$count integer

How many words from original string to include into truncated string.

$trimMarker string

String to append to the end of truncated string.

return string

The truncated string.

                public static function truncateWords(string $input, int $count, string $trimMarker = '…'): string
{
    /** @psalm-var list<string> $words */
    $words = preg_split('/(\s+)/u', trim($input), -1, PREG_SPLIT_DELIM_CAPTURE);
    if (count($words) / 2 > $count) {
        $words = array_slice($words, 0, ($count * 2) - 1);
        return implode('', $words) . $trimMarker;
    }
    return $input;
}

            
truncateWordsByLength() public static method

Truncates a string to the specified character length while preserving word boundaries.

public static string truncateWordsByLength ( string $input, integer $length, string $trimMarker '…', string $encoding 'UTF-8' )
$input string

The string to truncate.

$length integer

Maximum length of the truncated string including trim marker.

$trimMarker string

String to append to the end of truncated string.

$encoding string

The encoding to use, defaults to "UTF-8".

return string

The truncated string.

                public static function truncateWordsByLength(
    string $input,
    int $length,
    string $trimMarker = '…',
    string $encoding = 'UTF-8',
): string {
    $input = trim($input);
    if ($input === '') {
        return '';
    }
    if (mb_strlen($input, $encoding) <= $length) {
        return $input;
    }
    $markerLength = mb_strlen($trimMarker, $encoding);
    if ($length <= $markerLength) {
        return mb_substr($trimMarker, 0, $length, $encoding);
    }
    $truncated = mb_substr($input, 0, $length - $markerLength, $encoding);
    // Prefer not to break words if there's a space within the snippet.
    $lastSpace = mb_strrpos($truncated, ' ', 0, $encoding);
    if ($lastSpace !== false) {
        $cut = rtrim(mb_substr($truncated, 0, $lastSpace, $encoding));
        return $cut === ''
            ? mb_substr($trimMarker, 0, $length, $encoding)
            : $cut . $trimMarker;
    }
    return $truncated . $trimMarker;
}

            
uppercase() public static method

Make a string uppercase.

See also https://php.net/manual/en/function.mb-strtoupper.php.

public static string uppercase ( string $string, string $encoding 'UTF-8' )
$string string

String to process.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function uppercase(string $string, string $encoding = 'UTF-8'): string
{
    return mb_strtoupper($string, $encoding);
}

            
uppercaseFirstCharacter() public static method

Make a string's first character uppercase.

See also https://php.net/manual/en/function.ucfirst.php.

public static string uppercaseFirstCharacter ( string $string, string $encoding 'UTF-8' )
$string string

The string to be processed.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function uppercaseFirstCharacter(string $string, string $encoding = 'UTF-8'): string
{
    $firstCharacter = self::substring($string, 0, 1, $encoding);
    $rest = self::substring($string, 1, null, $encoding);
    return self::uppercase($firstCharacter, $encoding) . $rest;
}

            
uppercaseFirstCharacterInEachWord() public static method

Uppercase the first character of each word in a string.

See also https://php.net/manual/en/function.ucwords.php.

public static string uppercaseFirstCharacterInEachWord ( string $string, string $encoding 'UTF-8' )
$string string

The valid UTF-8 string to be processed.

$encoding string

The encoding to use, defaults to "UTF-8".

                public static function uppercaseFirstCharacterInEachWord(string $string, string $encoding = 'UTF-8'): string
{
    /**
     * @var array $words We assume that `$string` is valid UTF-8 string, so `preg_split()` never returns `false`.
     */
    $words = preg_split('/\s/u', $string, -1, PREG_SPLIT_NO_EMPTY);
    $wordsWithUppercaseFirstCharacter = array_map(
        static fn (string $word) => self::uppercaseFirstCharacter($word, $encoding),
        $words
    );
    return implode(' ', $wordsWithUppercaseFirstCharacter);
}