0 追蹤者

類別 yii\helpers\StringHelper

繼承關係yii\helpers\StringHelper » yii\helpers\BaseStringHelper
自版本2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/helpers/StringHelper.php

StringHelper。

公開方法

隱藏繼承方法

方法 描述 定義於
base64UrlDecode() 解碼 "Base 64 編碼與 URL 和檔案名稱安全字母" (RFC 4648)。 yii\helpers\BaseStringHelper
base64UrlEncode() 將字串編碼為 "Base 64 編碼與 URL 和檔案名稱安全字母" (RFC 4648)。 yii\helpers\BaseStringHelper
basename() 傳回路徑的尾端名稱組件。 yii\helpers\BaseStringHelper
byteLength() 傳回給定字串中的位元組數。 yii\helpers\BaseStringHelper
byteSubstr() 傳回字串中由 start 和 length 參數指定的部分。 yii\helpers\BaseStringHelper
countWords() 計算字串中的單字數。 yii\helpers\BaseStringHelper
dirname() 傳回父目錄的路徑。 yii\helpers\BaseStringHelper
endsWith() 檢查給定字串是否以指定的子字串結尾。二進制和多位元組安全。 yii\helpers\BaseStringHelper
explode() 將字串分解為陣列,可選擇修剪值並跳過空值。 yii\helpers\BaseStringHelper
findBetween() 傳回位於開始字串的第一次出現和結束字串的最後一次出現之間(之後)的字串部分。 yii\helpers\BaseStringHelper
floatToString() 安全地將浮點數轉換為字串,與目前地區設定無關。 yii\helpers\BaseStringHelper
mask() 使用重複的字元遮罩字串的一部分。 yii\helpers\BaseStringHelper
matchWildcard() 檢查傳遞的字串是否與給定的 shell 萬用字元模式匹配。 yii\helpers\BaseStringHelper
mb_ucfirst() 此方法提供內建 PHP 函數 ucfirst() 的 Unicode 安全實作。 yii\helpers\BaseStringHelper
mb_ucwords() 此方法提供內建 PHP 函數 ucwords() 的 Unicode 安全實作。 yii\helpers\BaseStringHelper
normalizeNumber() 如果目前地區設定的小數點是逗號,則傳回數字值的字串表示形式,並將逗號替換為點。 yii\helpers\BaseStringHelper
startsWith() 檢查給定字串是否以指定的子字串開頭。二進制和多位元組安全。 yii\helpers\BaseStringHelper
truncate() 將字串截斷為指定的字元數。 yii\helpers\BaseStringHelper
truncateWords() 將字串截斷為指定的單字數。 yii\helpers\BaseStringHelper

受保護方法

隱藏繼承方法

方法 描述 定義於
truncateHtml() 在保留 HTML 的同時截斷字串。 yii\helpers\BaseStringHelper

方法詳情

隱藏繼承方法

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

定義於: yii\helpers\BaseStringHelper::base64UrlDecode()

解碼 "Base 64 編碼與 URL 和檔案名稱安全字母" (RFC 4648)。

另請參閱 https://tools.ietf.org/html/rfc4648#page-7

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

已編碼的字串。

回傳 字串

已解碼的字串。

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

            
base64UrlEncode() public static 方法 (自版本 2.0.12 可用)

定義於: yii\helpers\BaseStringHelper::base64UrlEncode()

將字串編碼為 "Base 64 編碼與 URL 和檔案名稱安全字母" (RFC 4648)。

注意:Base 64 填充 = 可能會出現在回傳字串的末尾。= 對 URL 編碼不透明。

另請參閱 https://tools.ietf.org/html/rfc4648#page-7

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

要編碼的字串。

回傳 字串

已編碼的字串。

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

            
basename() public static 方法

定義於: yii\helpers\BaseStringHelper::basename()

傳回路徑的尾端名稱組件。

此方法與 php 的 basename() 函數相似,不同之處在於它會將 \ 和 / 都視為目錄分隔符號,而與作業系統無關。此方法主要用於處理 php 命名空間。當處理真實檔案路徑時,php 的 basename() 應該可以正常運作。注意:此方法不感知實際的檔案系統,或路徑組件,例如 "..".。

另請參閱 https://php.dev.org.tw/manual/en/function.basename.php

public static string basename ( $path, $suffix '' )
$path 字串

路徑字串。

$suffix 字串

如果名稱組件以 suffix 結尾,則也會被截斷。

回傳 字串

給定路徑的尾端名稱組件。

                public static function basename($path, $suffix = '')
{
    $path = (string)$path;
    $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 方法

定義於: yii\helpers\BaseStringHelper::byteLength()

傳回給定字串中的位元組數。

此方法確保字串被視為位元組陣列,透過使用 mb_strlen()

public static integer byteLength ( $string )
$string 字串

要測量長度的字串

回傳 整數

給定字串中的位元組數。

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

            
byteSubstr() public static 方法

定義於: yii\helpers\BaseStringHelper::byteSubstr()

傳回字串中由 start 和 length 參數指定的部分。

此方法確保字串被視為位元組陣列,透過使用 mb_substr()

另請參閱 https://php.dev.org.tw/manual/en/function.substr.php

public static string byteSubstr ( $string, $start, $length null )
$string 字串

輸入字串。必須為一個字元或更長。

$start 整數

起始位置

$length 整數|null

期望的部分長度。如果未指定或為 null,則長度將不受限制,即輸出將直到字串的末尾。

回傳 字串

字串的提取部分,或在失敗或空字串時回傳 FALSE。

                public static function byteSubstr($string, $start, $length = null)
{
    if ($length === null) {
        $length = static::byteLength($string);
    }
    return mb_substr((string)$string, $start, $length, '8bit');
}

            
countWords() public static 方法 (自版本 2.0.8 可用)

定義於: yii\helpers\BaseStringHelper::countWords()

計算字串中的單字數。

public static integer countWords ( $string )
$string 字串

要計算的文字

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

            
dirname() public static 方法

定義於: yii\helpers\BaseStringHelper::dirname()

傳回父目錄的路徑。

此方法與 dirname() 相似,不同之處在於它會將 \ 和 / 都視為目錄分隔符號,而與作業系統無關。

另請參閱 https://php.dev.org.tw/manual/en/function.basename.php

public static string dirname ( $path )
$path 字串

路徑字串。

回傳 字串

父目錄的路徑。

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

            
endsWith() public static 方法

定義於: yii\helpers\BaseStringHelper::endsWith()

檢查給定字串是否以指定的子字串結尾。二進制和多位元組安全。

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

要檢查的輸入字串

$with 字串

要在 $string 內部搜尋的部分。

$caseSensitive 布林值

區分大小寫搜尋。預設為 true。當啟用區分大小寫時,$with 必須完全符合字串的結尾才能取得 true 值。

回傳 布林值

如果第一個輸入以第二個輸入結尾,則回傳 true,否則回傳 false

                public static function endsWith($string, $with, $caseSensitive = true)
{
    $string = (string)$string;
    $with = (string)$with;
    if (!$bytes = static::byteLength($with)) {
        return true;
    }
    if ($caseSensitive) {
        // Warning check, see https://php.dev.org.tw/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 方法 (自版本 2.0.4 可用)

定義於: yii\helpers\BaseStringHelper::explode()

將字串分解為陣列,可選擇修剪值並跳過空值。

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

要被分割的字串。

$delimiter 字串

分隔符號。預設為 ','。

$trim 混合型別

是否修剪每個元素。可以是

  • 布林值 - 正常修剪;
  • 字串 - 要修剪的自訂字元。將作為第二個參數傳遞給 trim() 函數。
  • 可呼叫 - 將為每個值呼叫,而不是修剪。僅接受一個參數 - 值。
$skipEmpty 布林值

是否跳過分隔符號之間的空字串。預設為 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;
}

            
findBetween() public static 方法

定義於: yii\helpers\BaseStringHelper::findBetween()

傳回位於開始字串的第一次出現和結束字串的最後一次出現之間(之後)的字串部分。

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

輸入字串。

$start 字串

標記要提取部分開始位置的字串。

$end 字串

標記要提取部分結束位置的字串。

回傳 字串|null

字串中第一次出現 start 和最後一次出現 end 之間的部分,如果找不到 start 或 end,則為 null。

                public static function findBetween($string, $start, $end)
{
    $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);
}

            
floatToString() public static 方法 (自版本 2.0.13 可用)

定義於: yii\helpers\BaseStringHelper::floatToString()

安全地將浮點數轉換為字串,與目前地區設定無關。

小數點分隔符號將永遠是 .

public static string floatToString ( $number )
$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);
}

            
mask() public static 方法

定義於: yii\helpers\BaseStringHelper::mask()

使用重複的字元遮罩字串的一部分。

此方法是多位元組安全的。

public static string mask ( $string, $start, $length, $mask '*' )
$string 字串

輸入字串。

$start 整數

開始遮罩的起始位置。這可以是正整數或負整數。正值從頭開始計數,負值從字串末尾開始計數。

$length 整數

要遮罩的區段長度。遮罩將從 $start 位置開始,並持續 $length 個字元。

$mask 字串

用於遮罩的字元。預設為 '*'。

回傳 字串

已遮罩的字串。

                public static function mask($string, $start, $length, $mask = '*')
{
    $strLength = mb_strlen($string, 'UTF-8');
    // Return original string if start position is out of bounds
    if ($start >= $strLength || $start < -$strLength) {
        return $string;
    }
    $masked = mb_substr($string, 0, $start, 'UTF-8');
    $masked .= str_repeat($mask, abs($length));
    $masked .= mb_substr($string, $start + abs($length), null, 'UTF-8');
    return $masked;
}

            
matchWildcard() public static 方法 (自版本 2.0.14 可用)

定義於: yii\helpers\BaseStringHelper::matchWildcard()

檢查傳遞的字串是否與給定的 shell 萬用字元模式匹配。

此函數模擬 fnmatch(),它在某些環境中可能不可用,使用 PCRE。

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

Shell 萬用字元模式。

$string 字串

被測試的字串。

$options 陣列

匹配選項。有效選項為

  • caseSensitive: 布林值,模式是否應區分大小寫。預設為 true
  • escape: 布林值,是否啟用反斜線跳脫。預設為 true
  • filePath: 布林值,字串中的斜線是否僅匹配給定模式中的斜線。預設為 false
回傳 布林值

字串是否匹配模式。

                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 方法 (自版本 2.0.16 可用)

定義於: yii\helpers\BaseStringHelper::mb_ucfirst()

此方法提供內建 PHP 函數 ucfirst() 的 Unicode 安全實作。

另請參閱 https://php.dev.org.tw/manual/en/function.ucfirst.php

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

要處理的字串

$encoding 字串

可選,預設為 "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 方法 (自版本 2.0.16 可用)

定義於: yii\helpers\BaseStringHelper::mb_ucwords()

此方法提供內建 PHP 函數 ucwords() 的 Unicode 安全實作。

另請參閱 https://php.dev.org.tw/manual/en/function.ucwords

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

要處理的字串

$encoding 字串

可選,預設為 "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 方法 (自版本 2.0.11 可用)

定義於: yii\helpers\BaseStringHelper::normalizeNumber()

如果目前地區設定的小數點是逗號,則傳回數字值的字串表示形式,並將逗號替換為點。

public static string normalizeNumber ( $value )
$value 整數|浮點數|字串

要正規化的值。

                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 方法

定義於: yii\helpers\BaseStringHelper::startsWith()

檢查給定字串是否以指定的子字串開頭。二進制和多位元組安全。

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

輸入字串

$with 字串

要在 $string 內部搜尋的部分

$caseSensitive 布林值

區分大小寫搜尋。預設為 true。當啟用區分大小寫時,$with 必須完全符合字串的開頭才能取得 true 值。

回傳 布林值

如果第一個輸入以第二個輸入開頭,則回傳 true,否則回傳 false

                public static function startsWith($string, $with, $caseSensitive = true)
{
    $string = (string)$string;
    $with = (string)$with;
    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 方法

定義於: yii\helpers\BaseStringHelper::truncate()

將字串截斷為指定的字元數。

為了截斷到精確的長度,$suffix 字元長度必須計入 $length。例如,若要得到一個長度正好為 255 的字串,且 $suffix 為 ... (3 個字元),則必須使用 StringHelper::truncate($string, 252, '...') 以確保之後得到長度為 255 的字串。

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

要截斷的字串。

$length 整數

要從原始字串包含到截斷字串中的字元數。

$suffix 字串

要附加到截斷字串末尾的字串。

$encoding 字串|null

要使用的字元集,預設為應用程式目前使用的字元集。

$asHtml 布林值

是否將要截斷的字串視為 HTML 並保留正確的 HTML 標籤。此參數自版本 2.0.1 起可用。

回傳 字串

截斷後的字串。

                public static function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
{
    $string = (string)$string;
    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 方法 (自版本 2.0.1 可用)

定義於: yii\helpers\BaseStringHelper::truncateHtml()

在保留 HTML 的同時截斷字串。

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

要截斷的字串

$count 整數

計數器

$suffix 字串

要附加到截斷字串末尾的字串。

$encoding 字串|布林值

編碼標誌或字元集。

                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 方法

定義於: yii\helpers\BaseStringHelper::truncateWords()

將字串截斷為指定的單字數。

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

要截斷的字串。

$count 整數

要從原始字串包含到截斷字串中的單字數。

$suffix 字串

要附加到截斷字串末尾的字串。

$asHtml 布林值

是否將要截斷的字串視為 HTML 並保留正確的 HTML 標籤。此參數自版本 2.0.1 起可用。

回傳 字串

截斷後的字串。

                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;
}