Class luya\helpers\StringHelper
Inheritance | luya\helpers\StringHelper » luya\yii\helpers\StringHelper » yii\helpers\BaseStringHelper |
---|---|
Available since version | 1.0.0 |
Source Code | https://github.com/luyadev/luya/blob/master/core/helpers/StringHelper.php |
Helper methods when dealing with Strings.
Extends the {{yii\helpers\StringHelper}} class by some usefull functions like:
- {{luya\helpers\StringHelper::typeCast()}}
- {{luya\helpers\StringHelper::isFloat()}}
- {{luya\helpers\StringHelper::replaceFirst()}}
- {{luya\helpers\StringHelper::contains()}}
- {{luya\helpers\StringHelper::startsWithWildcard()}}
- {{luya\helpers\StringHelper::typeCastNumeric()}}
Public Methods
Method | Description | Defined By |
---|---|---|
base64UrlDecode() | Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648). | yii\helpers\BaseStringHelper |
base64UrlEncode() | Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648). | yii\helpers\BaseStringHelper |
basename() | Returns the trailing name component of a path. | yii\helpers\BaseStringHelper |
byteLength() | Returns the number of bytes in the given string. | yii\helpers\BaseStringHelper |
byteSubstr() | Returns the portion of string specified by the start and length parameters. | yii\helpers\BaseStringHelper |
contains() | Check whether a char or word exists in a string or not. | luya\yii\helpers\StringHelper |
countWords() | Counts words in a string. | yii\helpers\BaseStringHelper |
dirname() | Returns parent directory's path. | yii\helpers\BaseStringHelper |
endsWith() | Check if given string ends with specified substring. Binary and multibyte safe. | yii\helpers\BaseStringHelper |
explode() | Explodes string into array, optionally trims values and skips empty ones. | yii\helpers\BaseStringHelper |
filterMatch() | See if filter conditions match the given value. | luya\yii\helpers\StringHelper |
floatToString() | Safely casts a float to string independent of the current locale. | yii\helpers\BaseStringHelper |
highlightWord() | Highlight a word within a content. | luya\yii\helpers\StringHelper |
isFloat() | Checks whether a string is a float value. | luya\yii\helpers\StringHelper |
isNummeric() | Check whether a value is numeric or not. | luya\yii\helpers\StringHelper |
matchWildcard() | Checks if the passed string would match the given shell wildcard pattern. | yii\helpers\BaseStringHelper |
mb_str_split() | Multibyte-safe str_split funciton. | luya\yii\helpers\StringHelper |
mb_ucfirst() | This method provides a unicode-safe implementation of built-in PHP function ucfirst() . |
yii\helpers\BaseStringHelper |
mb_ucwords() | This method provides a unicode-safe implementation of built-in PHP function ucwords() . |
yii\helpers\BaseStringHelper |
minify() | "Minify" html content. | luya\yii\helpers\StringHelper |
normalizeNumber() | Returns string representation of number value with replaced commas to dots, if decimal point of current locale is comma. | yii\helpers\BaseStringHelper |
replaceFirst() | Replace only the first occurance found inside the string. | luya\yii\helpers\StringHelper |
sliceTransliteratedWord() | Search a word within a transliterated text and cut out the original word in the original text. | luya\yii\helpers\StringHelper |
startsWith() | Check if given string starts with specified substring. Binary and multibyte safe. | yii\helpers\BaseStringHelper |
startsWithWildcard() | String Wildcard Check. | luya\yii\helpers\StringHelper |
template() | Templating a string with Variables | luya\yii\helpers\StringHelper |
textList() | Convert a text with different seperators to an array. | luya\yii\helpers\StringHelper |
truncate() | Truncates a string to the number of characters specified. | yii\helpers\BaseStringHelper |
truncateMiddle() | Cut the given word/string from the content. Its truncates to the left side and to the right side of the word. | luya\yii\helpers\StringHelper |
truncateWords() | Truncates a string to the number of words specified. | yii\helpers\BaseStringHelper |
typeCast() | TypeCast a string to its specific types. | luya\yii\helpers\StringHelper |
typeCastNumeric() | TypeCast a numeric value to float or integer. | luya\yii\helpers\StringHelper |
Protected Methods
Method | Description | Defined By |
---|---|---|
truncateHtml() | Truncate a string while preserving the HTML. | yii\helpers\BaseStringHelper |
Method Details
Defined in: yii\helpers\BaseStringHelper::base64UrlDecode()
Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
public static string base64UrlDecode ( $input ) | ||
$input | string |
Encoded string. |
return | string |
Decoded string. |
---|
public static function base64UrlDecode($input)
{
return base64_decode(strtr($input, '-_', '+/'));
}
Defined in: yii\helpers\BaseStringHelper::base64UrlEncode()
Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
Note: Base 64 padding
=
may be at the end of the returned string.=
is not transparent to URL encoding.
public static string base64UrlEncode ( $input ) | ||
$input | string |
The string to encode. |
return | string |
Encoded string. |
---|
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 | string |
A path string. |
$suffix | string |
If the name component ends in suffix this will also be cut off. |
return | string |
The trailing name component of the given path. |
---|
public static function basename($path, $suffix = '')
{
$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;
}
Defined in: yii\helpers\BaseStringHelper::byteLength()
Returns the number of bytes in the given string.
This method ensures the string is treated as a byte array by using mb_strlen()
.
public static integer byteLength ( $string ) | ||
$string | string |
The string being measured for length |
return | integer |
The number of bytes in the given string. |
---|
public static function byteLength($string)
{
return mb_strlen((string)$string, '8bit');
}
Defined in: yii\helpers\BaseStringHelper::byteSubstr()
Returns the portion of string specified by the start and length parameters.
This method ensures the string is treated as a byte array by using mb_substr()
.
public static string byteSubstr ( $string, $start, $length = null ) | ||
$string | string |
The input string. Must be one character or longer. |
$start | integer |
The starting position |
$length | integer|null |
The desired portion length. If not specified or |
return | 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, $start, $length, '8bit');
}
Defined in: luya\yii\helpers\StringHelper::contains()
Check whether a char or word exists in a string or not.
This method is case sensitive. The need can be an array with multiple chars or words who are going to look up in the haystack string.
If an array of needle words is provided the $strict parameter defines whether all need keys must be found
in the string to get the true
response or if just one of the keys are found the response is already true
.
if (StringHelper::contains('foo', 'the foo bar Bar'')) {
echo "yes!";
}
check if one of the given needles exists:
if (StringHelper::contains(['jungle', 'hell0], 'Welcome to the jungle!)) {
echo "yes!";
}
public static boolean contains ( $needle, $haystack, $strict = false ) | ||
$needle | string|array |
The char or word to find in the $haystack. Can be an array to multi find words or char in the string. |
$haystack | string |
The haystack where the $needle string should be looked up. A string or phrase with words. |
$strict | boolean |
If an array of needles is provided the $strict parameter defines whether all keys must be found ($strict = true) or just one result must be found ($strict = false). |
return | boolean |
If an array of values is provided the response may change depending on $findAll. |
---|
public static function contains($needle, $haystack, $strict = false)
{
$needles = (array) $needle;
$state = false;
foreach ($needles as $item) {
$state = (strpos($haystack, (string) $item) !== false);
if ($strict && !$state) {
return false;
}
if (!$strict && $state) {
return true;
}
}
return $state;
}
Defined in: yii\helpers\BaseStringHelper::countWords()
Counts words in a string.
public static integer countWords ( $string ) | ||
$string | string |
The text to calculate |
public static function countWords($string)
{
return count(preg_split('/\s+/u', $string, 0, PREG_SPLIT_NO_EMPTY));
}
Defined in: yii\helpers\BaseStringHelper::dirname()
Returns parent directory's path.
This method is similar to dirname()
except that it will treat
both \ and / as directory separators, independent of the operating system.
See also https://www.php.net/manual/en/function.basename.php.
public static string dirname ( $path ) | ||
$path | string |
A path string. |
return | string |
The parent directory's path. |
---|
public static function dirname($path)
{
$normalizedPath = rtrim(
str_replace('\\', '/', $path),
'/'
);
$separatorPosition = mb_strrpos($normalizedPath, '/');
if ($separatorPosition !== false) {
return mb_substr($path, 0, $separatorPosition);
}
return '';
}
Defined in: yii\helpers\BaseStringHelper::endsWith()
Check if given string ends with specified substring. Binary and multibyte safe.
public static boolean endsWith ( $string, $with, $caseSensitive = true ) | ||
$string | string |
Input string to check |
$with | string |
Part to search inside of the |
$caseSensitive | boolean |
Case sensitive search. Default is true. When case sensitive is enabled, |
return | boolean |
Returns true if first input ends with second input, false otherwise |
---|
public static function endsWith($string, $with, $caseSensitive = true)
{
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);
}
Defined in: yii\helpers\BaseStringHelper::explode()
Explodes string into array, optionally trims values and skips empty ones.
public static array explode ( $string, $delimiter = ',', $trim = true, $skipEmpty = false ) | ||
$string | string |
String to be exploded. |
$delimiter | string |
Delimiter. Default is ','. |
$trim | mixed |
Whether to trim each element. Can be:
|
$skipEmpty | boolean |
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) {
// 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;
}
Defined in: luya\yii\helpers\StringHelper::filterMatch()
See if filter conditions match the given value.
Example filter conditions:
cms_*
matches everything starting with "cms_".cms_*,admin_*
matches booth cms* and admin* tables.!cms_*
matches all not start with "cms_"!cms_*,!admin_*
matches all not starting with "cms" and not starting with "admin"cms_*,!admin_*
matches all start with "cms" but not start with "admin"
Only first match is relevant:
- "cms*,!admin,admin_" include all cms* tables but exclude all admin* tables (last match has no effect)
- "cms*,admin,!admin_" include all cms* and admin* tables (last match has no effect)
Example using condition string:
filterMatch('hello', 'he*'); // true
filterMatch('hello', 'ho,he*'); // true
filterMatch('hello', ['ho', 'he*']); // true
public static boolean filterMatch ( $value, $conditions, $caseSensitive = true ) | ||
$value |
The value on which the filter conditions should be applied on. |
|
$conditions | array|string |
An array of filter conditions, if a string is given he will be exploded by commas. |
$caseSensitive | boolean |
Whether to match value even when lower/upper case is not correct/same. |
return | boolean |
Returns true if one of the given filter conditions matches. |
---|
public static function filterMatch($value, $conditions, $caseSensitive = true)
{
if (is_scalar($conditions)) {
$conditions = self::explode($conditions, ",", true, true);
}
foreach ($conditions as $condition) {
$isMatch = true;
// negate
if (substr($condition, 0, 1) == "!") {
$isMatch = false;
$condition = substr($condition, 1);
}
if ($caseSensitive) {
$condition = strtolower($condition);
$value = strtolower($value);
}
if ($condition == $value || self::startsWithWildcard($value, $condition)) {
return $isMatch;
}
}
return false;
}
Defined in: yii\helpers\BaseStringHelper::floatToString()
Safely casts a float to string independent of the current locale.
The decimal separator will always be .
.
public static string floatToString ( $number ) | ||
$number | float|integer |
A floating point number or integer. |
return | string |
The string representation of the 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);
}
Defined in: luya\yii\helpers\StringHelper::highlightWord()
Highlight a word within a content.
Since version 1.0.14 its possible to provide an array with words to highlight
This function IS NOT case sensitive!
StringHelper::highlightWord('Hello John!', 'john');
The above example would return Hello <b>John</b>!
.
public static void highlightWord ( $content, $word, $markup = '<b>%s</b>' ) | ||
$content | string |
The content to find the word. |
$word | string|array |
The word to find within the content. It can be an array. If a word exists already in the list of words, this one will be stripped. f.e. |
$markup | string |
The markup used wrap the word to highlight. |
public static function highlightWord($content, $word, $markup = '<b>%s</b>')
{
$transliterateContent = Inflector::transliterate($content);
$highlights = [];
$words = array_unique((array) $word);
// if there are multiple words, we need to ensure the same part of a word does not exists twice
// otherwise this can generate wrong highlight results like a highlight inside of a highlight.
if (count($words) > 1) {
foreach ($words as $wordIndex => $word) {
$inArrayIndex = preg_grep('/'.preg_quote($word).'/', $words);
if ((is_countable($inArrayIndex) ? count($inArrayIndex) : 0) > 1) {
unset($words[$wordIndex]);
}
}
}
foreach ($words as $word) {
// search in content
preg_match_all("/".preg_quote($word, '/')."+/i", $content, $matches);
foreach ($matches[0] as $word) {
$highlights[] = $word;
// if the word is covered already, do not process further in foreach and break here
break;
}
// search in transliated content if not yet breaked from previous results
preg_match_all("/".preg_quote($word, '/')."+/i", $transliterateContent, $matches);
foreach ($matches[0] as $word) {
$highlights[] = self::sliceTransliteratedWord($word, $transliterateContent, $content);
}
}
// hightlight all results in text with [[$word]]
foreach (array_unique($highlights) as $highlight) {
$content = str_replace($highlight, '[['.$highlight.']]', $content);
}
preg_match_all('/\[\[(.*?)\]\]/', $content, $matches, PREG_SET_ORDER);
$searchReplace = [];
foreach ($matches as $match) {
if (!array_key_exists($match[0], $searchReplace)) {
$searchReplace[$match[0]] = sprintf($markup, $match[1]);
}
}
foreach ($searchReplace as $search => $replace) {
$content = str_replace($search, $replace, $content);
}
return $content;
}
Defined in: luya\yii\helpers\StringHelper::isFloat()
Checks whether a string is a float value.
Compared to is_float
function of php, it only ensures whether the input variable is type float.
public static boolean isFloat ( $value ) | ||
$value | mixed |
The value to check whether its float or not. |
return | boolean |
Whether its a float value or not. |
---|
public static function isFloat($value)
{
if (is_float($value)) {
return true;
}
return ($value == (string)(float) $value);
}
Defined in: luya\yii\helpers\StringHelper::isNummeric()
Check whether a value is numeric or not.
There are situations where is_numeric does not provide the desried result,
like for example is_numeric('3e30')
would return true, as e can be considered
as exponential operator.
Therfore this function checks with regex whether values or 0-9 if strict is enabled, which is default behavior.
public static boolean isNummeric ( $value, $strict = true ) | ||
$value | mixed |
The value to check. |
$strict | boolean |
public static function isNummeric($value, $strict = true)
{
if (!is_scalar($value)) {
return false;
}
if (is_bool($value)) {
return false;
}
if ($strict) {
return preg_match('/^[0-9]+$/', $value) == 1 ? true : false;
}
return is_numeric($value);
}
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 | string |
The shell wildcard pattern. |
$string | string |
The tested string. |
$options | array |
Options for matching. Valid options are:
|
return | boolean |
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;
}
Defined in: luya\yii\helpers\StringHelper::mb_str_split()
Multibyte-safe str_split funciton.
See also https://www.php.net/manual/de/function.str-split.php#115703.
public static void mb_str_split ( $string, $length = 1 ) | ||
$string | string |
The string to split into an array |
$length | integer |
The length of the chars to cut. |
public static function mb_str_split($string, $length = 1)
{
return preg_split('/(.{'.$length.'})/us', $string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
}
Defined in: yii\helpers\BaseStringHelper::mb_ucfirst()
This method provides a unicode-safe implementation of built-in PHP function ucfirst()
.
See also https://www.php.net/manual/en/function.ucfirst.php.
public static string mb_ucfirst ( $string, $encoding = 'UTF-8' ) | ||
$string | string |
The string to be proceeded |
$encoding | string |
Optional, 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;
}
Defined in: yii\helpers\BaseStringHelper::mb_ucwords()
This method provides a unicode-safe implementation of built-in PHP function ucwords()
.
public static string mb_ucwords ( $string, $encoding = 'UTF-8' ) | ||
$string | string |
The string to be proceeded |
$encoding | string |
Optional, 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);
}
Defined in: luya\yii\helpers\StringHelper::minify()
"Minify" html content.
- remove space
- remove tabs
- remove newlines
- remove html comments
public static mixed minify ( $content, array $options = [] ) | ||
$content | string |
The content to minify. |
$options | array |
Optional arguments to provide for minification:
|
return | mixed |
Returns the minified content. |
---|
public static function minify($content, array $options = [])
{
$min = preg_replace(['/[\n\r]/', '/\>[^\S ]+/s', '/[^\S ]+\</s', '/(\s)+/s', ], ['', '>', '<', '\\1'], trim($content));
$min = str_replace(['> <'], ['><'], $min);
if (ArrayHelper::getValue($options, 'comments', false)) {
$min = preg_replace('/<!--(.*)-->/Uis', '', $min);
}
return $min;
}
Defined in: yii\helpers\BaseStringHelper::normalizeNumber()
Returns string representation of number value with replaced commas to dots, if decimal point of current locale is comma.
public static string normalizeNumber ( $value ) | ||
$value | integer|float|string |
The value to normalize. |
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;
}
Defined in: luya\yii\helpers\StringHelper::replaceFirst()
Replace only the first occurance found inside the string.
The replace first method is case sensitive.
StringHelper::replaceFirst('abc', '123', 'abc abc abc'); // returns "123 abc abc"
public static mixed replaceFirst ( $search, $replace, $subject ) | ||
$search | string |
Search string to look for. |
$replace | string |
Replacement value for the first found occurrence. |
$subject | string |
The string you want to look up to replace the first element. |
return | mixed |
Replaced string |
---|
public static function replaceFirst($search, $replace, $subject)
{
return preg_replace('/'.preg_quote($search, '/').'/', $replace, $subject, 1);
}
Defined in: luya\yii\helpers\StringHelper::sliceTransliteratedWord()
Search a word within a transliterated text and cut out the original word in the original text.
For example when you search for the transliaterad word in text and want to return the original:
StringHelper::sliceTransliteratedWord('frederic', 'Hello frederic', 'Hello fréderic');
The above example would return fréderic
public static string sliceTransliteratedWord ( $word, $transliteratedText, $originalText ) | ||
$word | string | |
$transliteratedText | string | |
$originalText | string |
public static function sliceTransliteratedWord($word, $transliteratedText, $originalText)
{
return mb_substr($originalText, mb_strpos($transliteratedText, $word), mb_strlen($word));
}
Defined in: yii\helpers\BaseStringHelper::startsWith()
Check if given string starts with specified substring. Binary and multibyte safe.
public static boolean startsWith ( $string, $with, $caseSensitive = true ) | ||
$string | string |
Input string |
$with | string |
Part to search inside the $string |
$caseSensitive | boolean |
Case sensitive search. Default is true. When case sensitive is enabled, |
return | boolean |
Returns true if first input starts with second input, false otherwise |
---|
public static function startsWith($string, $with, $caseSensitive = true)
{
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: luya\yii\helpers\StringHelper::startsWithWildcard()
String Wildcard Check.
Checks whether a strings starts with the wildcard symbole and compares the string before the wild card symbol * with the string provided, if there is NO wildcard symbold it always return false.
public static boolean startsWithWildcard ( $string, $with, $caseSensitive = true ) | ||
$string | string |
The string which should be checked with $with comperator |
$with | string |
The with string which must end with the wildcard symbol e.g. `foo |
$caseSensitive | boolean |
Whether to compare the starts with string as case sensitive or not, defaults to true. |
return | boolean |
Whether the string starts with the wildcard marked string or not, if no wildcard symbol is contained. in the $with it always returns false. |
---|
public static function startsWithWildcard($string, $with, $caseSensitive = true)
{
if (substr($with, -1) != "*") {
return false;
}
return self::startsWith($string, rtrim($with, '*'), $caseSensitive);
}
Defined in: luya\yii\helpers\StringHelper::template()
Templating a string with Variables
The variables should be declared as {{username}}
while the variables array key should contain username
.
Usage example:
$content = StringHelper::template('<p>{{ name }}</p>', ['name' => 'John']);
// output: <p>John</p>
If a variable is not found, the original curly bracktes will be returned.
public static string template ( $template, array $variables = [], $removeEmpty = false, $leftDelimiter = '{{', $rightDelimiter = '}}' ) | ||
$template | string |
The template to parse. The template may contain double curly brackets variables. |
$variables | array |
The variables which should be available in the template. |
$removeEmpty | boolean |
Whether variables in double curly brackets should be removed, even the have not be assigned by $variables array. |
$leftDelimiter | string |
The delimiter for the variable on the left, default is |
$rightDelimiter | string |
The delimiter for the variable on the right, default is |
public static function template($template, array $variables = [], $removeEmpty = false, $leftDelimiter = '{{', $rightDelimiter = '}}')
{
preg_match_all("/$leftDelimiter(.*?)$rightDelimiter/", $template, $matches, PREG_SET_ORDER);
if (empty($matches)) {
return $template;
}
foreach ($matches as $match) {
$exposedVariableName = trim($match[1]);
if (array_key_exists($exposedVariableName, $variables)) {
$template = str_replace($match[0], (string) $variables[$exposedVariableName], $template);
} elseif ($removeEmpty) {
$template = str_replace($match[0], '', $template);
}
}
return $template;
}
Defined in: luya\yii\helpers\StringHelper::textList()
Convert a text with different seperators to an array.
Its very common to use seperators when working with user input, for example a list of domains seperated by commas. Therefore this function will use common seperators the generate an array from a text string.
Explodes the string by: "Newline", ";", ","
- newline
- comma
- point comma
public static array textList ( $text, array $seperators = [PHP_EOL, "\n", "\r", "\n\r", ";", ","] ) | ||
$text | string |
A text which contains a list of items seperated by seperators like commas. |
$seperators |
public static function textList($text, array $seperators = [PHP_EOL, "\n", "\r", "\n\r", ";", ","])
{
return StringHelper::explode(str_replace($seperators, ';', $text), ";", true, true);
}
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.
public static string truncate ( $string, $length, $suffix = '...', $encoding = null, $asHtml = false ) | ||
$string | string |
The string to truncate. |
$length | integer |
How many characters from original string to include into truncated string. |
$suffix | string |
String to append to the end of truncated string. |
$encoding | string|null |
The charset to use, defaults to charset currently used by application. |
$asHtml | boolean |
Whether to treat the string being truncated as HTML and preserve proper HTML tags. This parameter is available since version 2.0.1. |
return | string |
The truncated string. |
---|
public static function truncate($string, $length, $suffix = '...', $encoding = null, $asHtml = false)
{
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;
}
Defined in: yii\helpers\BaseStringHelper::truncateHtml()
Truncate a string while preserving the HTML.
protected static string truncateHtml ( $string, $count, $suffix, $encoding = false ) | ||
$string | string |
The string to truncate |
$count | integer |
The counter |
$suffix | string |
String to append to the end of the truncated string. |
$encoding | string|boolean |
Encoding 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) { //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 : '');
}
Defined in: luya\yii\helpers\StringHelper::truncateMiddle()
Cut the given word/string from the content. Its truncates to the left side and to the right side of the word.
An example of how a sentenced is cut:
$cut = StringHelper::truncateMiddle('the quick fox jumped over the lazy dog', 'jumped', 12);
echo $cut; // ..e quick fox jumped over the la..
public static void truncateMiddle ( $content, $word, $length, $affix = '..', $caseSensitive = false ) | ||
$content | string |
The content to cut the words from. |
$word | string |
The word which should be in the middle of the string |
$length | integer |
The amount of the chars to cut on the left and right side from the word. |
$affix | string |
The chars which should be used for prefix and suffix when string is cuted. |
$caseSensitive | boolean |
Whether the search word in the string even when lower/upper case is not correct. |
public static function truncateMiddle($content, $word, $length, $affix = '..', $caseSensitive = false)
{
$content = strip_tags($content);
$array = self::mb_str_split($content);
$first = mb_strpos($caseSensitive ? $content : mb_strtolower($content), $caseSensitive ? $word : mb_strtolower($word));
// we could not find any match, therefore use casual truncate method.
if ($first === false) {
// as the length value in truncate middle stands for to the left and to the right, we multiple this value with 2
return self::truncate($content, ($length*2), $affix);
}
$last = $first + mb_strlen($word);
// left and right array chars from word
$left = array_slice($array, 0, $first, true);
$right = array_slice($array, $last, null, true);
$middle = array_splice($array, $first, mb_strlen($word));
// string before
$before = (count($left) > $length) ? $affix.implode("", array_slice($left, -$length)) : implode("", $left);
$after = (count($right) > $length) ? implode("", array_slice($right, 0, $length)) . $affix : implode("", $right);
return $before . implode("", $middle) . $after;
}
Defined in: yii\helpers\BaseStringHelper::truncateWords()
Truncates a string to the number of words specified.
public static string truncateWords ( $string, $count, $suffix = '...', $asHtml = false ) | ||
$string | string |
The string to truncate. |
$count | integer |
How many words from original string to include into truncated string. |
$suffix | string |
String to append to the end of truncated string. |
$asHtml | boolean |
Whether to treat the string being truncated as HTML and preserve proper HTML tags. This parameter is available since version 2.0.1. |
return | string |
The 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;
}
Defined in: luya\yii\helpers\StringHelper::typeCast()
TypeCast a string to its specific types.
Arrays will passed to to the {{luya\yii\helpers\ArrayHelper::typeCast()}} class.
public static mixed typeCast ( $string ) | ||
$string | mixed |
The input string to type cast. Arrays will be passted to {{luya\yii\helpers\ArrayHelper::typeCast()}}. |
return | mixed |
The new type casted value, if the input is an array the output is the typecasted array. |
---|
public static function typeCast($string)
{
if (is_numeric($string)) {
return static::typeCastNumeric($string);
} elseif (is_array($string)) {
return ArrayHelper::typeCast($string);
}
return $string;
}
Defined in: luya\yii\helpers\StringHelper::typeCastNumeric()
TypeCast a numeric value to float or integer.
If the given value is not a numeric or float value it will be returned as it is. In order to find out whether its float or not use {{luya\yii\helpers\StringHelper::isFloat()}}.
public static mixed typeCastNumeric ( $value ) | ||
$value | mixed |
The given value to parse. |
return | mixed |
Returns the original value if not numeric or integer, float casted value. |
---|
public static function typeCastNumeric($value)
{
if (!self::isFloat($value)) {
return $value;
}
if (intval($value) == $value) {
return (int) $value;
}
return (float) $value;
}