StringHelper.
public static function base64UrlDecode($input)
{
return base64_decode(strtr($input, '-_', '+/'));
}
public static function base64UrlEncode($input)
{
return strtr(base64_encode($input), '+/', '-_');
}
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 stringA path string.
$suffix stringIf the name component ends in suffix this will also be cut off.
return stringThe trailing name component of the given path.
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;
}
public static integer byteLength ( $string ) $string string
The string being measured for length
return integerThe number of bytes in the given string.
public static function byteLength($string)
{
return mb_strlen((string)$string, '8bit');
}
public static string byteSubstr ( $string, $start, $length = null ) $string string
The input string. Must be one character or longer.
$start integerThe starting position
$length integer|nullThe 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.
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)$string, $start, $length, '8bit');
}
public static function countWords($string)
{
return count(preg_split('/\s+/u', $string, 0, PREG_SPLIT_NO_EMPTY));
}
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 string
Input string to check
$with stringPart to search inside of the $string
.
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.
Returns true if first input ends with second input, false otherwise
public static function endsWith($string, $with, $caseSensitive = true)
{
$string = (string)$string;
$with = (string)$with;
if (!$bytes = static::byteLength($with)) {
return true;
}
if ($caseSensitive) {
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 string
String to be exploded.
$delimiter stringDelimiter. Default is ','.
$trim mixedWhether to trim each element. Can be:
trim()
function.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) {
$result = array_values(
array_filter(
$result,
function ($value) {
return $value !== '';
}
)
);
}
return $result;
}
public static string|null findBetween ( $string, $start, $end ) $string string
The input string.
$start stringThe string marking the start of the portion to extract.
$end stringThe string marking the end of the portion to extract.
return string|nullThe portion of the string between the first occurrence of start and the last occurrence of end, or null if either start or end cannot be found.
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 function floatToString($number)
{
return str_replace(',', '.', (string)$number);
}
public static string mask ( $string, $start, $length, $mask = '*' ) $string string
The input string.
$start integerThe starting position from where to begin masking. This can be a positive or negative integer. Positive values count from the beginning, negative values count from the end of the string.
$length integerThe length of the section to be masked. The masking will start from the $start position and continue for $length characters.
$mask stringThe character to use for masking. The default is '*'.
return stringThe masked string.
public static function mask($string, $start, $length, $mask = '*')
{
$strLength = mb_strlen($string, 'UTF-8');
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;
}
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 stringThe shell wildcard pattern.
$string stringThe tested string.
$options arrayOptions for matching. Valid options are:
true
.true
.false
.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;
}
public static string mb_ucfirst ( $string, $encoding = 'UTF-8' ) $string string
The string to be proceeded
$encoding stringOptional, 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;
}
public static string mb_ucwords ( $string, $encoding = 'UTF-8' ) $string string
The string to be proceeded
$encoding stringOptional, 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);
}
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 string
Input string
$with stringPart to search inside the $string
$caseSensitive booleanCase 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.
Returns true if first input starts with second input, false otherwise
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);
}
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.
The string to truncate.
$length integerHow many characters from original string to include into truncated string.
$suffix stringString to append to the end of truncated string.
$encoding string|nullThe charset to use, defaults to charset currently used by application.
$asHtml booleanWhether to treat the string being truncated as HTML and preserve proper HTML tags. This parameter is available since version 2.0.1.
return stringThe truncated 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;
}
protected static string truncateHtml ( $string, $count, $suffix, $encoding = false ) $string string
The string to truncate
$count integerThe counter
$suffix stringString to append to the end of the truncated string.
$encoding string|booleanEncoding 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) {
$openTokens[$depth] = $token->name;
$truncated[] = $token;
++$depth;
} elseif ($token instanceof \HTMLPurifier_Token_Text && $totalCount <= $count) {
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) {
if ($token->name === $openTokens[$depth - 1]) {
--$depth;
unset($openTokens[$depth]);
$truncated[] = $token;
}
} elseif ($token instanceof \HTMLPurifier_Token_Empty) {
$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 string
The string to truncate.
$count integerHow many words from original string to include into truncated string.
$suffix stringString to append to the end of truncated string.
$asHtml booleanWhether to treat the string being truncated as HTML and preserve proper HTML tags. This parameter is available since version 2.0.1.
return stringThe 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;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4