クラス 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() | 「URLおよびファイル名セーフアルファベットを使用したBase 64エンコーディング」(RFC 4648) をデコードします。 | yii\helpers\BaseStringHelper |
base64UrlEncode() | 文字列を「URLおよびファイル名セーフアルファベットを使用したBase 64エンコーディング」(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() | 渡された文字列が指定されたシェルワイルドカードパターンに一致するかどうかを確認します。 | 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 |
メソッドの詳細
「URLおよびファイル名セーフアルファベットを使用したBase 64エンコーディング」(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, '-_', '+/'));
}
文字列を「URLおよびファイル名セーフアルファベットを使用したBase 64エンコーディング」(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), '+/', '-_');
}
パスの末尾のコンポーネント名を返します。
このメソッドはphp関数 `basename()` と似ていますが、オペレーティングシステムに依存せず、`\` と `/` の両方をディレクトリセパレータとして扱います。このメソッドは主にphp名前空間で動作するために作成されました。実際のファイルパスを操作する場合は、phpの `basename()` で問題なく動作するはずです。注: このメソッドは実際のファイルシステムまたは「..」などのパスコンポーネントを認識しません。
こちらも参照してください https://www.php.net/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;
}
指定された文字列のバイト数を返します。
このメソッドは、mb_strlen()
を使用することで、文字列をバイト配列として扱うことを保証します。
public static integer byteLength ( $string ) | ||
$string | 文字列 |
長さを測定する文字列 |
戻り値 | integer |
指定された文字列のバイト数。 |
---|
public static function byteLength($string)
{
return mb_strlen((string)$string, '8bit');
}
start および length パラメータで指定された文字列の部分を返します。
このメソッドは、mb_substr()
を使用することで、文字列をバイト配列として扱うことを保証します。
こちらも参照してください https://www.php.net/manual/en/function.substr.php.
public static string byteSubstr ( $string, $start, $length = null ) | ||
$string | 文字列 |
入力文字列。1文字以上である必要があります。 |
$start | integer |
開始位置 |
$length | integer|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');
}
文字列内の単語数をカウントします。
public static integer countWords ( $string ) | ||
$string | 文字列 |
計算するテキスト |
public static function countWords($string)
{
return count(preg_split('/\s+/u', $string, 0, PREG_SPLIT_NO_EMPTY));
}
親ディレクトリのパスを返します。
このメソッドはdirname()
に似ていますが、オペレーティングシステムに関係なく、\と/の両方をディレクトリセパレータとして扱います。
こちらも参照してください https://www.php.net/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 '';
}
指定された部分文字列で文字列が終了するかどうかを確認します。バイナリおよびマルチバイトセーフです。
public static boolean endsWith ( $string, $with, $caseSensitive = true ) | ||
$string | 文字列 |
チェックする入力文字列 |
$with | 文字列 |
|
$caseSensitive | boolean |
大文字と小文字を区別する検索。デフォルトはtrueです。大文字と小文字を区別する検索が有効になっている場合、true値を取得するには、 |
戻り値 | boolean |
最初の入力が2番目の入力で終わる場合は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.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);
}
文字列を配列に分割し、オプションで値をトリミングし、空の値をスキップします。
public static array explode ( $string, $delimiter = ',', $trim = true, $skipEmpty = false ) | ||
$string | 文字列 |
分割される文字列。 |
$delimiter | 文字列 |
デリミタ。デフォルトは','です。 |
$trim | mixed |
各要素をトリムするかどうか。
|
$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;
}
開始文字列の最初の出現と、その後の終了文字列の最後の出現の間に存在する文字列の部分を返します。
public static string|null findBetween ( $string, $start, $end ) | ||
$string | 文字列 |
入力文字列。 |
$start | 文字列 |
抽出する部分の開始を示す文字列。 |
$end | 文字列 |
抽出する部分の終了を示す文字列。 |
戻り値 | string|null |
開始の最初の出現箇所と終了の最後の出現箇所の間の文字列の部分、または開始または終了が見つからない場合は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);
}
現在のロケールに依存しない、安全な浮動小数点数の文字列表現へのキャストを行います。
小数点セパレータは常に.
になります。
public static string floatToString ( $number ) | ||
$number | float|integer |
浮動小数点数または整数。 |
戻り値 | 文字列 |
数値の文字列表現。 |
---|
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);
}
文字列の一部を繰り返し文字でマスクします。
このメソッドはマルチバイトに対応しています。
public static string mask ( $string, $start, $length, $mask = '*' ) | ||
$string | 文字列 |
入力文字列。 |
$start | integer |
マスキングを開始する開始位置。正または負の整数にすることができます。正の値は先頭からカウントし、負の値は文字列の末尾からカウントします。 |
$length | integer |
マスキングするセクションの長さ。マスキングは$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;
}
渡された文字列が指定されたシェルワイルドカードパターンに一致するかどうかを確認します。
この関数は、特定の環境では利用できない可能性のあるfnmatch()をPCREを使用してエミュレートします。
public static boolean matchWildcard ( $pattern, $string, $options = [] ) | ||
$pattern | 文字列 |
シェルワイルドカードパターン。 |
$string | 文字列 |
テスト対象の文字列。 |
$options | 配列 |
マッチングのためのオプション。有効なオプションは以下の通りです。
|
戻り値 | 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;
}
このメソッドは、組み込みのPHP関数 `ucfirst()` のUnicode対応実装を提供します。
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;
}
このメソッドは、組み込みのPHP関数 `ucwords()` のUnicode対応実装を提供します。
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);
}
現在のロケールの小数点がカンマの場合、カンマをピリオドに置き換えた数値の文字列表現を返します。
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;
}
指定された部分文字列で文字列が開始するかどうかを確認します。バイナリおよびマルチバイトセーフです。
public static boolean startsWith ( $string, $with, $caseSensitive = true ) | ||
$string | 文字列 |
入力文字列 |
$with | 文字列 |
$string 内で検索する部分 |
$caseSensitive | boolean |
大文字と小文字を区別する検索。デフォルトは true です。大文字と小文字を区別する場合、 |
戻り値 | boolean |
最初の入力が2番目の入力で始まる場合は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);
}
指定された文字数まで文字列を切り詰めます。
正確な長さで切り捨てるには、$suffix 文字の長さを$lengthに含める必要があります。たとえば、$suffix `...` (3文字) を含めて文字列を正確に255文字にするには、`StringHelper::truncate($string, 252, '...')` を使用して、結果の文字列が255文字になるようにする必要があります。
public static string truncate ( $string, $length, $suffix = '...', $encoding = null, $asHtml = false ) | ||
$string | 文字列 |
切り捨てる文字列。 |
$length | integer |
元の文字列から切り詰めた文字列に含める文字数。 |
$suffix | 文字列 |
切り詰めた文字列の最後に追加する文字列。 |
$encoding | string|null |
使用する文字セット。デフォルトはアプリケーションで現在使用されている文字セット。 |
$asHtml | boolean |
切り捨てられる文字列を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;
}
HTMLを保持したまま文字列を切り詰めます。
protected static string truncateHtml ( $string, $count, $suffix, $encoding = false ) | ||
$string | 文字列 |
切り捨てる文字列 |
$count | integer |
カウンター |
$suffix | 文字列 |
切り詰めた文字列の最後に追加する文字列。 |
$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 : '');
}
指定された単語数まで文字列を切り詰めます。
public static string truncateWords ( $string, $count, $suffix = '...', $asHtml = false ) | ||
$string | 文字列 |
切り捨てる文字列。 |
$count | integer |
元の文字列から切り詰めた文字列に含める単語数。 |
$suffix | 文字列 |
切り詰めた文字列の最後に追加する文字列。 |
$asHtml | boolean |
切り捨てられる文字列を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;
}
サインアップ または ログイン してコメントしてください。