クラス yii\helpers\StringHelper
継承 | yii\helpers\StringHelper » yii\helpers\BaseStringHelper |
---|---|
利用可能なバージョン | 2.0 |
ソースコード | https://github.com/yiisoft/yii2/blob/master/framework/helpers/StringHelper.php |
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() | 開始パラメータと長さパラメータで指定された文字列の部分を返します。 | yii\helpers\BaseStringHelper |
countWords() | 文字列内の単語数をカウントします。 | yii\helpers\BaseStringHelper |
dirname() | 親ディレクトリのパスを返します。 | yii\helpers\BaseStringHelper |
endsWith() | 指定された部分文字列で文字列が終了するかどうかをチェックします。バイナリとマルチバイトに対応しています。 | yii\helpers\BaseStringHelper |
explode() | 文字列を配列に分割し、オプションで値をトリミングし、空の値をスキップします。 | yii\helpers\BaseStringHelper |
findBetween() | 開始文字列の最初の出現と、その後の終了文字列の最後の出現の間に存在する文字列の部分を返します。 | yii\helpers\BaseStringHelper |
floatToString() | 現在のロケールに依存せずに、floatを安全に文字列に変換します。 | 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 |
メソッドの詳細
定義元: yii\helpers\BaseStringHelper::base64UrlDecode()
「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, '-_', '+/'));
}
定義元: yii\helpers\BaseStringHelper::base64UrlEncode()
文字列を「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), '+/', '-_');
}
定義元: yii\helpers\BaseStringHelper::basename()
パスの末尾のコンポーネント名を取得します。
このメソッドは、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;
}
定義元: yii\helpers\BaseStringHelper::byteLength()
指定された文字列のバイト数を返します。
このメソッドは、`mb_strlen()`を使用して文字列をバイト配列として扱うことを保証します。
public static integer byteLength ( $string ) | ||
$string | 文字列 |
長さを測定する文字列 |
戻り値 | 整数 |
指定された文字列のバイト数。 |
---|
public static function byteLength($string)
{
return mb_strlen((string)$string, '8bit');
}
定義位置: yii\helpers\BaseStringHelper::byteSubstr()
開始パラメータと長さパラメータで指定された文字列の部分を返します。
このメソッドは、mb_substr()
を使用することで、文字列をバイト配列として扱うことを保証します。
public static string byteSubstr ( $string, $start, $length = null ) | ||
$string | 文字列 |
入力文字列。1文字以上である必要があります。 |
$start | 整数 |
開始位置 |
$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');
}
定義位置: 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));
}
定義位置: yii\helpers\BaseStringHelper::dirname()
親ディレクトリのパスを返します。
このメソッドは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 '';
}
定義位置: yii\helpers\BaseStringHelper::endsWith()
指定された部分文字列で文字列が終了するかどうかをチェックします。バイナリとマルチバイトに対応しています。
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);
}
定義位置: yii\helpers\BaseStringHelper::explode()
文字列を配列に分割し、オプションで値をトリミングし、空の値をスキップします。
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;
}
定義位置: yii\helpers\BaseStringHelper::findBetween()
開始文字列の最初の出現と、その後の終了文字列の最後の出現の間に存在する文字列の部分を返します。
public static string|null findBetween ( $string, $start, $end ) | ||
$string | 文字列 |
入力文字列。 |
$start | 文字列 |
抽出する部分の開始を示す文字列。 |
$end | 文字列 |
抽出する部分の終了を示す文字列。 |
戻り値 | 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);
}
定義位置: yii\helpers\BaseStringHelper::floatToString()
現在のロケールに依存せずに、floatを安全に文字列に変換します。
小数点セパレータは常に.
になります。
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 | 整数 |
マスキングを開始する開始位置。正または負の整数にすることができます。正の値は先頭から数え、負の値は文字列の末尾から数えます。 |
$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;
}
定義位置: yii\helpers\BaseStringHelper::matchWildcard()
渡された文字列が指定されたシェルワイルドカードパターンに一致するかどうかを確認します。
この関数は、特定の環境では使用できない可能性のあるfnmatch()をPCREを使用してエミュレートします。
public static ブール値 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;
}
定義されている場所: yii\helpers\BaseStringHelper::mb_ucfirst()
このメソッドは、組み込みのPHP関数`ucfirst()`のUnicode対応の実装を提供します。
こちらも参照してください https://www.php.net/manual/en/function.ucfirst.php.
public static 文字列 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;
}
定義されている場所: yii\helpers\BaseStringHelper::mb_ucwords()
このメソッドは、組み込みのPHP関数`ucwords()`のUnicode対応の実装を提供します。
こちらも参照してください https://www.php.net/manual/en/function.ucwords.
public static 文字列 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);
}
定義されている場所: yii\helpers\BaseStringHelper::normalizeNumber()
現在のロケールの小数点がカンマの場合、カンマをピリオドに置き換えた数値の文字列表現を返します。
public static 文字列 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;
}
定義されている場所: yii\helpers\BaseStringHelper::startsWith()
指定された部分文字列で文字列が始まるかどうかをチェックします。バイナリとマルチバイトに対応しています。
public static ブール値 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);
}
定義されている場所: yii\helpers\BaseStringHelper::truncate()
指定された文字数まで文字列を切り詰めます。
正確な長さに切り詰めるには、$suffix文字の長さを$lengthに含める必要があります。たとえば、$suffixが'...'(3文字)で正確に255文字の長さの文字列にするには、StringHelper::truncate($string, 252, '...')
を使用する必要があります。
public static 文字列 truncate ( $string, $length, $suffix = '...', $encoding = null, $asHtml = false ) | ||
$string | 文字列 |
切り詰める文字列。 |
$length | 整数 |
元の文字列から切り詰めた文字列に含める文字数。 |
$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;
}
定義されている場所: yii\helpers\BaseStringHelper::truncateHtml()
HTMLを保持しながら文字列を切り詰めます。
protected static 文字列 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 : '');
}
定義されている場所: yii\helpers\BaseStringHelper::truncateWords()
指定された単語数まで文字列を切り詰めます。
public static 文字列 truncateWords ( $string, $count, $suffix = '...', $asHtml = false ) | ||
$string | 文字列 |
切り詰める文字列。 |
$count | 整数 |
元の文字列から切り詰めた文字列に含める単語数。 |
$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;
}
コメントするにはサインアップまたはログインしてください。