0 追蹤者

類別 yii\helpers\BaseStringHelper

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

BaseStringHelper 為 yii\helpers\StringHelper 提供具體實作。

請勿使用 BaseStringHelper。請改用 yii\helpers\StringHelper

公開方法

隱藏繼承方法

方法 描述 定義於
base64UrlDecode() 解碼 "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648)。 yii\helpers\BaseStringHelper
base64UrlEncode() 將字串編碼為 "Base 64 Encoding with URL and Filename Safe Alphabet" (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 (自版本 2.0.12 起可用)

解碼 "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648)。

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

public static string base64UrlDecode ( $input )
$input string

編碼後的字串。

return string

解碼後的字串。

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

            
base64UrlEncode() public static method (自版本 2.0.12 起可用)

將字串編碼為 "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648)。

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

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

public static string base64UrlEncode ( $input )
$input string

要編碼的字串。

return string

編碼後的字串。

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

            
basename() public static method

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

這個方法與 php 的 basename() 函數類似,不同之處在於它會將 \ 和 / 都視為目錄分隔符號,而與作業系統無關。此方法主要用於處理 php 命名空間。當處理真實檔案路徑時,php 的 basename() 函數應該就能滿足您的需求。請注意:此方法無法感知實際的檔案系統或路徑組件,例如「..」。

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

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

路徑字串。

$suffix string

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

return string

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

                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 method

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

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

public static integer byteLength ( $string )
$string string

要測量長度的字串

return integer

給定字串中的位元組數。

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

            
byteSubstr() public static method

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

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

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

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

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

$start integer

起始位置

$length integer|null

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

return string

字串的提取部分,失敗或空字串時為 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 method (自 2.0.8 版本起可用)

計算字串中的單字數。

public static integer countWords ( $string )
$string string

要計算的文字

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

            
dirname() public static method

傳回父目錄的路徑。

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

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

public static string dirname ( $path )
$path string

路徑字串。

return string

父目錄的路徑。

                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 method

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

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

要檢查的輸入字串

$with string

要在 $string 內搜尋的部分。

$caseSensitive boolean

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

return boolean

如果第一個輸入以第二個輸入結尾,則返回 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 method (自 2.0.4 版本起可用)

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

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

要被分割的字串。

$delimiter string

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

$trim mixed

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

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

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

傳回字串中位於起始字串的第一次出現和其後結束字串的最後一次出現之間的部分。

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

輸入字串。

$start string

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

$end string

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

return string|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 method (自 2.0.13 版本起可用)

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

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

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

浮點數或整數。

return string

數字的字串表示形式。

                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 method

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

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

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

輸入字串。

$start integer

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

$length integer

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

$mask string

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

return string

已遮罩的字串。

                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 method (自 2.0.14 版本起可用)

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

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

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

shell 萬用字元模式。

$string string

被測試的字串。

$options array

匹配選項。有效選項為

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

字串是否符合模式。

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

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

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

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

要處理的字串

$encoding string

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

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

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

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

要處理的字串

$encoding string

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

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

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

要標準化的值。

                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

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

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

輸入字串

$with string

要在 $string 內搜尋的部分

$caseSensitive boolean

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

return boolean

如果第一個輸入以第二個輸入開始,則返回 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 method

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

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

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

要截斷的字串。

$length integer

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

$suffix string

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

$encoding string|null

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

$asHtml boolean

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

return string

截斷後的字串。

                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 method (自 2.0.1 版本起可用)

截斷字串,同時保留 HTML。

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

要截斷的字串

$count integer

計數器

$suffix string

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

$encoding string|boolean

編碼標誌或字元集。

                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

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

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

要截斷的字串。

$count integer

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

$suffix string

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

$asHtml boolean

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

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