Class yii\helpers\StringHelper

Inheritanceyii\helpers\StringHelper » yii\helpers\BaseStringHelper
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/helpers/StringHelper.php

StringHelper.

Public Methods

Hide inherited methods

Method Description Defined By
base64UrlDecode() Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648). yii\helpers\BaseStringHelper
base64UrlEncode() Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648). yii\helpers\BaseStringHelper
basename() Returns the trailing name component of a path. yii\helpers\BaseStringHelper
byteLength() Returns the number of bytes in the given string. yii\helpers\BaseStringHelper
byteSubstr() Returns the portion of string specified by the start and length parameters. yii\helpers\BaseStringHelper
countWords() Counts words in a string. yii\helpers\BaseStringHelper
dirname() Returns parent directory's path. yii\helpers\BaseStringHelper
endsWith() Check if given string ends with specified substring. Binary and multibyte safe. yii\helpers\BaseStringHelper
explode() Explodes string into array, optionally trims values and skips empty ones. yii\helpers\BaseStringHelper
floatToString() Safely casts a float to string independent of the current locale. yii\helpers\BaseStringHelper
matchWildcard() Checks if the passed string would match the given shell wildcard pattern. yii\helpers\BaseStringHelper
mb_ucfirst() This method provides a unicode-safe implementation of built-in PHP function ucfirst(). yii\helpers\BaseStringHelper
mb_ucwords() This method provides a unicode-safe implementation of built-in PHP function ucwords(). yii\helpers\BaseStringHelper
normalizeNumber() Returns string representation of number value with replaced commas to dots, if decimal point of current locale is comma. yii\helpers\BaseStringHelper
startsWith() Check if given string starts with specified substring. Binary and multibyte safe. yii\helpers\BaseStringHelper
truncate() Truncates a string to the number of characters specified. yii\helpers\BaseStringHelper
truncateWords() Truncates a string to the number of words specified. yii\helpers\BaseStringHelper

Protected Methods

Hide inherited methods

Method Description Defined By
truncateHtml() Truncate a string while preserving the HTML. yii\helpers\BaseStringHelper

Method Details

Hide inherited methods

base64UrlDecode() public static method (available since version 2.0.12)

Defined in: yii\helpers\BaseStringHelper::base64UrlDecode()

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 ( $input )
$input string

Encoded string.

return string

Decoded string.

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

            
base64UrlEncode() public static method (available since version 2.0.12)

Defined in: yii\helpers\BaseStringHelper::base64UrlEncode()

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 ( $input )
$input string

The string to encode.

return string

Encoded string.

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

            
basename() public static method

Defined in: yii\helpers\BaseStringHelper::basename()

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 ( $path, $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($path, $suffix = '')
{
    $len = mb_strlen($suffix);
    if ($len > 0 && mb_substr($path, -$len) === $suffix) {
        $path = mb_substr($path, 0, -$len);
    }
    $path = rtrim(str_replace('\\', '/', $path), '/');
    $pos = mb_strrpos($path, '/');
    if ($pos !== false) {
        return mb_substr($path, $pos + 1);
    }
    return $path;
}

            
byteLength() public static method

Defined in: yii\helpers\BaseStringHelper::byteLength()

Returns the number of bytes in the given string.

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

public static integer byteLength ( $string )
$string string

The string being measured for length

return integer

The number of bytes in the given string.

                public static function byteLength($string)
{
    return mb_strlen((string)$string, '8bit');
}

            
byteSubstr() public static method

Defined in: yii\helpers\BaseStringHelper::byteSubstr()

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 byteSubstr ( $string, $start, $length null )
$string 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 byteSubstr($string, $start, $length = null)
{
    if ($length === null) {
        $length = static::byteLength($string);
    }
    return mb_substr($string, $start, $length, '8bit');
}

            
countWords() public static method (available since version 2.0.8)

Defined in: yii\helpers\BaseStringHelper::countWords()

Counts words in a string.

public static integer countWords ( $string )
$string string

The text to calculate

                public static function countWords($string)
{
    return count(preg_split('/\s+/u', $string, 0, PREG_SPLIT_NO_EMPTY));
}

            
dirname() public static method

Defined in: yii\helpers\BaseStringHelper::dirname()

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 dirname ( $path )
$path string

A path string.

return string

The parent directory's path.

                public static function dirname($path)
{
    $normalizedPath = rtrim(
        str_replace('\\', '/', $path),
        '/'
    );
    $separatorPosition = mb_strrpos($normalizedPath, '/');
    if ($separatorPosition !== false) {
        return mb_substr($path, 0, $separatorPosition);
    }
    return '';
}

            
endsWith() public static method

Defined in: yii\helpers\BaseStringHelper::endsWith()

Check if given string ends with specified substring. Binary and multibyte safe.

public static boolean endsWith ( $string, $with, $caseSensitive true )
$string string

Input string to check

$with string

Part to search inside of the $string.

$caseSensitive boolean

Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the ending of the string in order to get a true value.

return boolean

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

                public static function endsWith($string, $with, $caseSensitive = true)
{
    if (!$bytes = static::byteLength($with)) {
        return true;
    }
    if ($caseSensitive) {
        // Warning check, see https://php.net/substr-compare#refsect1-function.substr-compare-returnvalues
        if (static::byteLength($string) < $bytes) {
            return false;
        }
        return substr_compare($string, $with, -$bytes, $bytes) === 0;
    }
    $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
    $string = static::byteSubstr($string, -$bytes);
    return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
}

            
explode() public static method (available since version 2.0.4)

Defined in: yii\helpers\BaseStringHelper::explode()

Explodes string into array, optionally trims values and skips empty ones.

public static array explode ( $string, $delimiter ',', $trim true, $skipEmpty false )
$string string

String to be exploded.

$delimiter string

Delimiter. Default is ','.

$trim mixed

Whether to trim each element. Can be:

  • boolean - to trim normally;
  • string - custom characters to trim. Will be passed as a second argument to trim() function.
  • callable - will be called for each value instead of trim. Takes the only argument - value.
$skipEmpty boolean

Whether to skip empty strings between delimiters. Default is false.

                public static function explode($string, $delimiter = ',', $trim = true, $skipEmpty = false)
{
    $result = explode($delimiter, $string);
    if ($trim !== false) {
        if ($trim === true) {
            $trim = 'trim';
        } elseif (!is_callable($trim)) {
            $trim = function ($v) use ($trim) {
                return trim($v, $trim);
            };
        }
        $result = array_map($trim, $result);
    }
    if ($skipEmpty) {
        // Wrapped with array_values to make array keys sequential after empty values removing
        $result = array_values(array_filter($result, function ($value) {
            return $value !== '';
        }));
    }
    return $result;
}

            
floatToString() public static method (available since version 2.0.13)

Defined in: yii\helpers\BaseStringHelper::floatToString()

Safely casts a float to string independent of the current locale.

The decimal separator will always be ..

public static string floatToString ( $number )
$number float|integer

A floating point number or integer.

return string

The string representation of the number.

                public static function floatToString($number)
{
    // . and , are the only decimal separators known in ICU data,
    // so its safe to call str_replace here
    return str_replace(',', '.', (string) $number);
}

            
matchWildcard() public static method (available since version 2.0.14)

Defined in: yii\helpers\BaseStringHelper::matchWildcard()

Checks if the passed string would match the given shell wildcard pattern.

This function emulates fnmatch(), which may be unavailable at certain environment, using PCRE.

public static boolean matchWildcard ( $pattern, $string, $options = [] )
$pattern string

The shell wildcard pattern.

$string string

The tested string.

$options array

Options for matching. Valid options are:

  • caseSensitive: bool, whether pattern should be case sensitive. Defaults to true.
  • escape: bool, whether backslash escaping is enabled. Defaults to true.
  • filePath: bool, whether slashes in string only matches slashes in the given pattern. Defaults to false.
return boolean

Whether the string matches pattern or not.

                public static function matchWildcard($pattern, $string, $options = [])
{
    if ($pattern === '*' && empty($options['filePath'])) {
        return true;
    }
    $replacements = [
        '\\\\\\\\' => '\\\\',
        '\\\\\\*' => '[*]',
        '\\\\\\?' => '[?]',
        '\*' => '.*',
        '\?' => '.',
        '\[\!' => '[^',
        '\[' => '[',
        '\]' => ']',
        '\-' => '-',
    ];
    if (isset($options['escape']) && !$options['escape']) {
        unset($replacements['\\\\\\\\']);
        unset($replacements['\\\\\\*']);
        unset($replacements['\\\\\\?']);
    }
    if (!empty($options['filePath'])) {
        $replacements['\*'] = '[^/\\\\]*';
        $replacements['\?'] = '[^/\\\\]';
    }
    $pattern = strtr(preg_quote($pattern, '#'), $replacements);
    $pattern = '#^' . $pattern . '$#us';
    if (isset($options['caseSensitive']) && !$options['caseSensitive']) {
        $pattern .= 'i';
    }
    return preg_match($pattern, (string)$string) === 1;
}

            
mb_ucfirst() public static method (available since version 2.0.16)

Defined in: yii\helpers\BaseStringHelper::mb_ucfirst()

This method provides a unicode-safe implementation of built-in PHP function ucfirst().

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

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

The string to be proceeded

$encoding string

Optional, defaults to "UTF-8"

                public static function mb_ucfirst($string, $encoding = 'UTF-8')
{
    $firstChar = mb_substr((string)$string, 0, 1, $encoding);
    $rest = mb_substr((string)$string, 1, null, $encoding);
    return mb_strtoupper($firstChar, $encoding) . $rest;
}

            
mb_ucwords() public static method (available since version 2.0.16)

Defined in: yii\helpers\BaseStringHelper::mb_ucwords()

This method provides a unicode-safe implementation of built-in PHP function ucwords().

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

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

The string to be proceeded

$encoding string

Optional, defaults to "UTF-8"

                public static function mb_ucwords($string, $encoding = 'UTF-8')
{
    $string = (string) $string;
    if (empty($string)) {
        return $string;
    }
    $parts = preg_split('/(\s+\W+\s+|^\W+\s+|\s+)/u', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    $ucfirstEven = trim(mb_substr($parts[0], -1, 1, $encoding)) === '';
    foreach ($parts as $key => $value) {
        $isEven = (bool)($key % 2);
        if ($ucfirstEven === $isEven) {
            $parts[$key] = static::mb_ucfirst($value, $encoding);
        }
    }
    return implode('', $parts);
}

            
normalizeNumber() public static method (available since version 2.0.11)

Defined in: yii\helpers\BaseStringHelper::normalizeNumber()

Returns string representation of number value with replaced commas to dots, if decimal point of current locale is comma.

public static string normalizeNumber ( $value )
$value integer|float|string

The value to normalize.

                public static function normalizeNumber($value)
{
    $value = (string) $value;
    $localeInfo = localeconv();
    $decimalSeparator = isset($localeInfo['decimal_point']) ? $localeInfo['decimal_point'] : null;
    if ($decimalSeparator !== null && $decimalSeparator !== '.') {
        $value = str_replace($decimalSeparator, '.', $value);
    }
    return $value;
}

            
startsWith() public static method

Defined in: yii\helpers\BaseStringHelper::startsWith()

Check if given string starts with specified substring. Binary and multibyte safe.

public static boolean startsWith ( $string, $with, $caseSensitive true )
$string string

Input string

$with string

Part to search inside the $string

$caseSensitive boolean

Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the starting of the string in order to get a true value.

return boolean

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

                public static function startsWith($string, $with, $caseSensitive = true)
{
    if (!$bytes = static::byteLength($with)) {
        return true;
    }
    if ($caseSensitive) {
        return strncmp($string, $with, $bytes) === 0;
    }
    $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
    $string = static::byteSubstr($string, 0, $bytes);
    return mb_strtolower($string, $encoding) === mb_strtolower($with, $encoding);
}

            
truncate() public static method

Defined in: yii\helpers\BaseStringHelper::truncate()

Truncates a string to the number of characters specified.

In order to truncate for an exact length, the $suffix char length must be counted towards the $length. For example to have a string which is exactly 255 long with $suffix ... of 3 chars, then StringHelper::truncate($string, 252, '...') must be used to ensure you have 255 long string afterwards.

public static string truncate ( $string, $length, $suffix '...', $encoding null, $asHtml false )
$string string

The string to truncate.

$length integer

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

$suffix string

String to append to the end of truncated string.

$encoding string|null

The charset to use, defaults to charset currently used by application.

$asHtml boolean

Whether to treat the string being truncated as HTML and preserve proper HTML tags. This parameter is available since version 2.0.1.

return string

The truncated string.

                public static function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
{
    if ($encoding === null) {
        $encoding = Yii::$app ? Yii::$app->charset : 'UTF-8';
    }
    if ($asHtml) {
        return static::truncateHtml($string, $length, $suffix, $encoding);
    }
    if (mb_strlen($string, $encoding) > $length) {
        return rtrim(mb_substr($string, 0, $length, $encoding)) . $suffix;
    }
    return $string;
}

            
truncateHtml() protected static method (available since version 2.0.1)

Defined in: yii\helpers\BaseStringHelper::truncateHtml()

Truncate a string while preserving the HTML.

protected static string truncateHtml ( $string, $count, $suffix, $encoding false )
$string string

The string to truncate

$count integer

The counter

$suffix string

String to append to the end of the truncated string.

$encoding string|boolean

Encoding flag or charset.

                protected static function truncateHtml($string, $count, $suffix, $encoding = false)
{
    $config = \HTMLPurifier_Config::create(null);
    if (Yii::$app !== null) {
        $config->set('Cache.SerializerPath', Yii::$app->getRuntimePath());
    }
    $lexer = \HTMLPurifier_Lexer::create($config);
    $tokens = $lexer->tokenizeHTML($string, $config, new \HTMLPurifier_Context());
    $openTokens = [];
    $totalCount = 0;
    $depth = 0;
    $truncated = [];
    foreach ($tokens as $token) {
        if ($token instanceof \HTMLPurifier_Token_Start) { //Tag begins
            $openTokens[$depth] = $token->name;
            $truncated[] = $token;
            ++$depth;
        } elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) { //Text
            if (false === $encoding) {
                preg_match('/^(\s*)/um', $token->data, $prefixSpace) ?: $prefixSpace = ['', ''];
                $token->data = $prefixSpace[1] . self::truncateWords(ltrim($token->data), $count - $totalCount, '');
                $currentCount = self::countWords($token->data);
            } else {
                $token->data = self::truncate($token->data, $count - $totalCount, '', $encoding);
                $currentCount = mb_strlen($token->data, $encoding);
            }
            $totalCount += $currentCount;
            $truncated[] = $token;
        } elseif ($token instanceof \HTMLPurifier_Token_End) { //Tag ends
            if ($token->name === $openTokens[$depth - 1]) {
                --$depth;
                unset($openTokens[$depth]);
                $truncated[] = $token;
            }
        } elseif ($token instanceof \HTMLPurifier_Token_Empty) { //Self contained tags, i.e. <img/> etc.
            $truncated[] = $token;
        }
        if ($totalCount >= $count) {
            if (0 < count($openTokens)) {
                krsort($openTokens);
                foreach ($openTokens as $name) {
                    $truncated[] = new \HTMLPurifier_Token_End($name);
                }
            }
            break;
        }
    }
    $context = new \HTMLPurifier_Context();
    $generator = new \HTMLPurifier_Generator($config, $context);
    return $generator->generateFromTokens($truncated) . ($totalCount >= $count ? $suffix : '');
}

            
truncateWords() public static method

Defined in: yii\helpers\BaseStringHelper::truncateWords()

Truncates a string to the number of words specified.

public static string truncateWords ( $string, $count, $suffix '...', $asHtml false )
$string string

The string to truncate.

$count integer

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

$suffix string

String to append to the end of truncated string.

$asHtml boolean

Whether to treat the string being truncated as HTML and preserve proper HTML tags. This parameter is available since version 2.0.1.

return string

The truncated string.

                public static function truncateWords($string, $count, $suffix = '...', $asHtml = false)
{
    if ($asHtml) {
        return static::truncateHtml($string, $count, $suffix);
    }
    $words = preg_split('/(\s+)/u', trim($string), 0, PREG_SPLIT_DELIM_CAPTURE);
    if (count($words) / 2 > $count) {
        return implode('', array_slice($words, 0, ($count * 2) - 1)) . $suffix;
    }
    return $string;
}