StringHelper

Type
Class
Namespace
craft\helpers
Inherits
craft\helpers\StringHelper » yii\helpers\StringHelper (opens new window) » yii\helpers\BaseStringHelper (opens new window)
Since
3.0.0

This helper class provides various multi-byte aware string related manipulation and encoding methods.

View source (opens new window)

# Public Methods

Method Description
UUID() Generates a valid v4 UUID string. See [http://stackoverflow.com/a/2040279/684]
afterFirst() Gets the substring after the first occurrence of a separator.
afterLast() Gets the substring after the last occurrence of a separator.
append() Returns a new string with $append appended.
appendRandomString() Returns a new string with a random string appended to it.
appendUniqueIdentifier() Returns a new string with a unique identifier appended to it.
asciiCharMap() Returns ASCII character mappings, merging in any custom defined mappings from the config3:customAsciiCharMappings (opens new window) config setting.
at() Returns the character at $index, with indexes starting at 0.
base64UrlDecode() (opens new window) Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
base64UrlEncode() (opens new window) Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
basename() (opens new window) Returns the trailing name component of a path.
beforeFirst() Gets the substring before the first occurrence of a separator.
beforeLast() Gets the substring before the last occurrence of a separator.
between() Returns the substring between $start and $end, if found, or an empty string.
byteLength() (opens new window) Returns the number of bytes in the given string.
byteSubstr() (opens new window) Returns the portion of string specified by the start and length parameters.
camelCase() Returns a camelCase version of the given string. Trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, as well as underscores.
capitalizePersonalName() Returns the string with the first letter of each word capitalized, except for when the word is a name which shouldn't be capitalized.
charsAsArray() Returns an array consisting of the characters in the string.
collapseWhitespace() Trims the string and replaces consecutive whitespace characters with a single space. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.
contains() Returns true if the string contains $needle, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
containsAll() Returns true if the string contains all $needles, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
containsAny() Returns true if the string contains any $needles, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
containsMb4() Detects whether the given string has any 4-byte UTF-8 characters.
convertToUtf8() Attempts to convert a string to UTF-8 and clean any non-valid UTF-8 characters.
count() Returns the length of the string, implementing the countable interface.
countSubstrings() Returns the number of occurrences of $substring in the given string. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
countWords() (opens new window) Counts words in a string.
dasherize() Returns a lowercase and trimmed string separated by dashes. Dashes are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces as well as underscores.
decdec() Base64-decodes and decrypts a string generated by encenc().
delimit() Returns a lowercase and trimmed string separated by the given delimiter. Delimiters are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces, dashes, and underscores. Alpha delimiters are not converted to lowercase.
dirname() (opens new window) Returns parent directory's path.
encenc() Encrypts and base64-encodes a string.
encodeMb4() HTML-encodes any 4-byte UTF-8 characters.
encoding() Gets the encoding of the given string.
endsWith() (opens new window) Check if given string ends with specified substring.
endsWithAny() Returns true if the string ends with any of $substrings, false otherwise.
ensureLeft() Ensures that the string begins with $substring. If it doesn't, it's prepended.
ensureRight() Ensures that the string ends with $substring. If it doesn't, it's appended.
escape() Create a escape html version of the string via "$this->utf8::htmlspecialchars()".
explode() (opens new window) Explodes string into array, optionally trims values and skips empty ones.
extractText() Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
first() Returns the first $n characters of the string.
floatToString() (opens new window) Safely casts a float to string independent of the current locale.
hasLowerCase() Returns whether the given string has any lowercase characters in it.
hasUpperCase() Returns whether the given string has any uppercase characters in it.
htmlDecode() Convert all HTML entities to their applicable characters.
htmlEncode() Convert all applicable characters to HTML entities.
humanize() Capitalizes the first word of the string, replaces underscores with spaces, and strips '_id'.
idnToUtf8Email() Converts an email from IDNA ASCII to Unicode, if the Intl extension is installed.
indexOf() Returns the index of the first occurrence of $needle in the string, and false if not found.
indexOfLast() Returns the index of the last occurrence of $needle in the string, and false if not found. Accepts an optional offset from which to begin the search. Offsets may be negative to count from the last character in the string.
insert() Inserts $substring into the string at the $index provided.
is() Returns true if the string contains the $pattern, otherwise false.
isAlpha() Returns true if the string contains only alphabetic chars, false otherwise.
isAlphanumeric() Returns true if the string contains only alphabetic and numeric chars, false otherwise.
isBase64() Returns true if the string is base64 encoded, false otherwise.
isBlank() Returns true if the string contains only whitespace chars, false otherwise.
isHexadecimal() Returns true if the string contains only hexadecimal chars, false otherwise.
isHtml() Returns true if the string contains HTML-Tags, false otherwise.
isJson() Returns true if the string is JSON, false otherwise. Unlike json_decode in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers, in that an empty string is not considered valid JSON.
isLowerCase() Returns true if the string contains only lower case chars, false otherwise.
isSerialized() Returns true if the string is serialized, false otherwise.
isUUID() Returns is the given string matches a v4 UUID pattern.
isUpperCase() Returns true if the string contains only upper case chars, false otherwise.
isUtf8() Checks if the given string is UTF-8 encoded.
isWhitespace() Returns true if the string contains only whitespace chars, false otherwise.
last() Returns the last $number characters of the string.
lastSubstringOf() Returns the last $number characters of the string.
length() Returns the length of the string. An alias for PHP's mb_strlen() function.
lineWrapAfterWord() Line wrap the string after $limit, but also after the next word.
lines() Splits on newlines and carriage returns, returning an array of strings corresponding to the lines in the string.
lowercaseFirst() Converts the first character of the supplied string to lower case.
matchWildcard() (opens new window) Checks if the passed string would match the given shell wildcard pattern.
mb_ucfirst() (opens new window) This method provides a unicode-safe implementation of built-in PHP function ucfirst().
mb_ucwords() (opens new window) This method provides a unicode-safe implementation of built-in PHP function ucwords().
normalizeNumber() (opens new window) Returns string representation of number value with replaced commas to dots, if decimal point of current locale is comma.
pad() Pads the string to a given length with $padStr. If length is less than or equal to the length of the string, no padding takes places. The default string used for padding is a space, and the default type (one of 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException if $padType isn't one of those 3 values.
padBoth() Returns a new string of a given length such that both sides of the string are padded. Alias for pad() with a $padType of 'both'.
padLeft() Returns a new string of a given length such that the beginning of the string is padded. Alias for pad() with a $padType of 'left'.
padRight() Returns a new string of a given length such that the end of the string is padded. Alias for pad() with a $padType of 'right'.
prepend() Returns a new string starting with $string.
randomString() Generates a random string of latin alphanumeric characters that defaults to a $length of 36. If $extendedChars is set to true, additional symbols can be included in the string. Note that the generated string is not a cryptographically secure string. If you need a cryptographically secure string, use Craft::$app->security->generateRandomString() (opens new window).
randomStringWithChars() Generates a random string of characters. Note that the generated string is not a cryptographically secure string. If you need a cryptographically secure string, use Craft::$app->security->generateRandomString() (opens new window).
regexReplace() Replaces all occurrences of $pattern in $str by $replacement. An alias for mb_ereg_replace().
removeHtml() Remove html via "strip_tags()" from the string.
removeHtmlBreak() Remove all breaks [
removeLeft() Returns a new string with the prefix $substring removed, if present.
removeRight() Returns a new string with the suffix $substring removed, if present.
repeat() Returns a repeated string given a multiplier.
replace() Replaces all occurrences of $search in $str by $replacement.
replaceAll() Replaces all occurrences of $search in $str by $replacement.
replaceBeginning() Replaces all occurrences of $search from the beginning of string with $replacement.
replaceEnding() Replaces all occurrences of $search from the beginning of string with $replacement.
replaceFirst() Replaces first occurrences of $search from the beginning of string with $replacement.
replaceLast() Replaces last occurrences of $search from the ending of string with $replacement.
replaceMb4() Replaces 4-byte UTF-8 characters in a string.
reverse() Returns a reversed string. A multibyte version of strrev().
safeTruncate() Truncates the string to a given length, while ensuring that it does not split words. If $substring is provided, and truncating occurs, the string is further truncated so that the substring may be appended without exceeding the desired length.
shortenAfterWord() Shorten the string after $length, but also after the next word.
shuffle() Shorten the string after $length, but also after the next word.
slice() Returns the substring beginning at $start, and up to, but not including the index specified by $end. If $end is omitted, the function extracts the remaining string. If $end is negative, it is computed from the end of the string.
slugify() Converts the string into an URL slug. This includes replacing non-ASCII characters with their closest ASCII equivalents, removing remaining non-ASCII and non-alphanumeric characters, and replacing whitespace with $replacement. The replacement defaults to a single dash, and the string is also converted to lowercase. The language of the source string can also be supplied for language-specific transliteration.
split() Splits a string into chunks on a given delimiter.
splitOnWords() Splits a string into an array of the words in the string.
startsWith() Returns true if the string begins with $substring, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
startsWithAny() Returns true if the string begins with any of $substrings, false otherwise.
stripCssMediaQueries() Remove CSS media-queries.
stripEmptyHtmlTags() Remove any empty HTML tags.
stripHtml() Strips HTML tags out of a given string.
stripWhitespace() Strip all whitespace characters. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.
substr() Returns the substring beginning at $start with the specified
substringOf() Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
surround() Surrounds $str with the given substring.
swapCase() Returns a case swapped version of the string.
tidy() Returns a string with smart quotes, ellipsis characters, and dashes from Windows-1252 (commonly used in Word documents) replaced by their ASCII equivalents.
titleize() Returns a trimmed string with the first letter of each word capitalized. Ignores the case of other letters, preserving any acronyms. Also accepts an array, $ignore, allowing you to list words not to be capitalized.
titleizeForHumans() Returns a trimmed string in proper title case.
toAscii() Returns an ASCII version of the string. A set of non-ASCII characters are replaced with their closest ASCII counterparts, and the rest are removed.
toBoolean() Returns a boolean representation of the given logical string value.
toCamelCase() CamelCases a string.
toKebabCase() Kebab-cases a string.
toLowerCase() Converts all characters in the string to lowercase. An alias for PHP's mb_strtolower().
toPascalCase() PascalCases a string.
toSnakeCase() Snake_cases a string.
toSpaces() Converts each tab in the string to some number of spaces, as defined by $tabLength. By default, each tab is converted to 4 consecutive spaces.
toString() Converts an object to its string representation. If the object is an array, will glue the array elements togeter with the $glue param. Otherwise will cast the object to a string.
toTabs() Converts each occurrence of some consecutive number of spaces, as defined by $tabLength, to a tab. By default, each 4 consecutive spaces are converted to a tab.
toTitleCase() Converts the first character of each word in the string to uppercase.
toTransliterate() Returns an ASCII version of the string. A set of non-ASCII characters are replaced with their closest ASCII counterparts, and the rest are removed unless instructed otherwise.
toUpperCase() Converts all characters in the string to uppercase. An alias for PHP's mb_strtoupper().
toWords() Returns an array of words extracted from a string
trim() Returns a string with whitespace removed from the start and end of the string. Supports the removal of unicode whitespace. Accepts an optional string of characters to strip instead of the defaults.
trimLeft() Returns a string with whitespace removed from the start of the string.
trimRight() Returns a string with whitespace removed from the end of the string.
truncate() (opens new window) Truncates a string to the number of characters specified.
truncateWords() (opens new window) Truncates a string to the number of words specified.
upperCamelize() Returns an UpperCamelCase version of the supplied string. It trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, underscores.
upperCaseFirst() Converts the first character of the supplied string to uppercase.

# UUID()

Generates a valid v4 UUID string. See [http://stackoverflow.com/a/2040279/684]

View source (opens new window)

Returns

string (opens new window) – The UUID.

Throws

# afterFirst()

Since
3.3.0

Gets the substring after the first occurrence of a separator.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string.

# afterLast()

Since
3.3.0

Gets the substring after the last occurrence of a separator.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string.

# append()

Since
3.3.0

Returns a new string with $append appended.

View source (opens new window)

Arguments

Returns

string (opens new window) – The newly appended string.

# appendRandomString()

Since
3.3.0

Returns a new string with a random string appended to it.

View source (opens new window)

Arguments

Returns

string (opens new window) – The newly appended string.

# appendUniqueIdentifier()

Since
3.3.0

Returns a new string with a unique identifier appended to it.

View source (opens new window)

Arguments

Returns

string (opens new window) – The newly appended string.

# asciiCharMap()

Returns ASCII character mappings, merging in any custom defined mappings from the config3:customAsciiCharMappings (opens new window) config setting.

View source (opens new window)

Arguments

Returns

array (opens new window) – The fully merged ASCII character mappings.

# at()

Since
3.3.0

Returns the character at $index, with indexes starting at 0.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting character.

# beforeFirst()

Since
3.3.0

Gets the substring before the first occurrence of a separator.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string.

# beforeLast()

Since
3.3.0

Gets the substring before the last occurrence of a separator.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string.

# between()

Returns the substring between $start and $end, if found, or an empty string.

An optional offset may be supplied from which to begin the search for the start string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string.

# camelCase()

Returns a camelCase version of the given string. Trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, as well as underscores.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string in camelCase.

# capitalizePersonalName()

Since
3.3.0

Returns the string with the first letter of each word capitalized, except for when the word is a name which shouldn't be capitalized.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with personal names capitalized.

# charsAsArray()

Returns an array consisting of the characters in the string.

View source (opens new window)

Arguments

Returns

string (opens new window)[] – An array of string chars

# collapseWhitespace()

Trims the string and replaces consecutive whitespace characters with a single space. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.

View source (opens new window)

Arguments

Returns

string (opens new window) – The trimmed string with condensed whitespace.

# contains()

Returns true if the string contains $needle, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $haystack contains $needle.

# containsAll()

Returns true if the string contains all $needles, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $haystack contains all $needles.

# containsAny()

Returns true if the string contains any $needles, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $haystack contains any $needles.

# containsMb4()

Detects whether the given string has any 4-byte UTF-8 characters.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the string contains any 4-byte UTF-8 characters or not.

# convertToUtf8()

Attempts to convert a string to UTF-8 and clean any non-valid UTF-8 characters.

View source (opens new window)

Arguments

Returns

string (opens new window)

# count()

Since
3.3.0

Returns the length of the string, implementing the countable interface.

View source (opens new window)

Arguments

Returns

integer (opens new window) – The length of the string.

# countSubstrings()

Returns the number of occurrences of $substring in the given string. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

View source (opens new window)

Arguments

Returns

integer (opens new window) – The number of $substring occurrences.

# dasherize()

Since
3.3.0

Returns a lowercase and trimmed string separated by dashes. Dashes are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces as well as underscores.

View source (opens new window)

Arguments

Returns

string (opens new window) – The dasherized string.

# decdec()

Base64-decodes and decrypts a string generated by encenc().

View source (opens new window)

Arguments

Returns

string (opens new window)

Throws

# delimit()

Returns a lowercase and trimmed string separated by the given delimiter. Delimiters are inserted before uppercase characters (with the exception of the first character of the string), and in place of spaces, dashes, and underscores. Alpha delimiters are not converted to lowercase.

View source (opens new window)

Arguments

Returns

string (opens new window) – The delimited string.

# encenc()

Encrypts and base64-encodes a string.

See also decdec() View source (opens new window)

Arguments

Returns

string (opens new window)

Throws

# encodeMb4()

HTML-encodes any 4-byte UTF-8 characters.

See also http://stackoverflow.com/a/16496730/1688568 View source (opens new window)

Arguments

Returns

string (opens new window) – The string with converted 4-byte UTF-8 characters

# encoding()

Gets the encoding of the given string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The encoding of the string.

# endsWithAny()

Since
3.3.0

Returns true if the string ends with any of $substrings, false otherwise.

By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str ends with $substring.

# ensureLeft()

Ensures that the string begins with $substring. If it doesn't, it's prepended.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string prefixed by the $substring.

# ensureRight()

Ensures that the string ends with $substring. If it doesn't, it's appended.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string suffixed by the $substring.

# escape()

Since
3.3.0

Create a escape html version of the string via "$this->utf8::htmlspecialchars()".

View source (opens new window)

Arguments

Returns

string (opens new window) – The string to escape.

# extractText()

Since
3.3.0

Create an extract from a sentence, so if the search-string was found, it try to centered in the output.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string to escape.

# first()

Returns the first $n characters of the string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The first $number characters.

# hasLowerCase()

Returns whether the given string has any lowercase characters in it.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – If the string has a lowercase character or not.

# hasUpperCase()

Returns whether the given string has any uppercase characters in it.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – If the string has an uppercase character or not.

# htmlDecode()

Since
3.3.0

Convert all HTML entities to their applicable characters.

View source (opens new window)

Arguments

Returns

string (opens new window) – The decoded string.

# htmlEncode()

Since
3.3.0

Convert all applicable characters to HTML entities.

View source (opens new window)

Arguments

Returns

string (opens new window) – The encoded string.

# humanize()

Since
3.3.0

Capitalizes the first word of the string, replaces underscores with spaces, and strips '_id'.

View source (opens new window)

Arguments

Returns

string (opens new window) – The humanized string.

# idnToUtf8Email()

Since
3.5.16

Converts an email from IDNA ASCII to Unicode, if the Intl extension is installed.

View source (opens new window)

Arguments

Returns

string (opens new window)

# indexOf()

Returns the index of the first occurrence of $needle in the string, and false if not found.

Accepts an optional offset from which to begin the search.

View source (opens new window)

Arguments

Returns

integer (opens new window), boolean (opens new window) – The occurrence's index if found, otherwise false.

# indexOfLast()

Returns the index of the last occurrence of $needle in the string, and false if not found. Accepts an optional offset from which to begin the search. Offsets may be negative to count from the last character in the string.

View source (opens new window)

Arguments

Returns

integer (opens new window), boolean (opens new window) – The occurrence's last index if found, otherwise false.

# insert()

Inserts $substring into the string at the $index provided.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the insertion

# is()

Since
3.3.0

Returns true if the string contains the $pattern, otherwise false.

WARNING: Asterisks ("") are translated into (".") zero-or-more regular expression wildcards.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not we match the provided pattern.

# isAlpha()

Returns true if the string contains only alphabetic chars, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str contains only alphabetic chars.

# isAlphanumeric()

Returns true if the string contains only alphabetic and numeric chars, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str contains only alphanumeric chars.

# isBase64()

Since
3.3.0

Returns true if the string is base64 encoded, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str is base64 encoded.

# isBlank()

Since
3.3.0

Returns true if the string contains only whitespace chars, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str contains only whitespace characters.

# isHexadecimal()

Since
3.3.0

Returns true if the string contains only hexadecimal chars, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str contains only hexadecimal chars.

# isHtml()

Since
3.3.0

Returns true if the string contains HTML-Tags, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str contains HTML tags.

# isJson()

Since
3.3.0

Returns true if the string is JSON, false otherwise. Unlike json_decode in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers, in that an empty string is not considered valid JSON.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str is JSON.

# isLowerCase()

Returns true if the string contains only lower case chars, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str is only lower case characters.

# isSerialized()

Since
3.3.0

Returns true if the string is serialized, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str is serialized.

# isUUID()

Returns is the given string matches a v4 UUID pattern.

Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the string matches a v4 UUID pattern.

# isUpperCase()

Returns true if the string contains only upper case chars, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str contains only lower case characters.

# isUtf8()

Since
3.3.0

Checks if the given string is UTF-8 encoded.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the string was UTF encoded or not.

# isWhitespace()

Since
3.3.0

Returns true if the string contains only whitespace chars, false otherwise.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str contains only whitespace characters.

# last()

Returns the last $number characters of the string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The last $number characters.

# lastSubstringOf()

Since
3.3.0

Returns the last $number characters of the string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The last $number characters.

# length()

Returns the length of the string. An alias for PHP's mb_strlen() function.

View source (opens new window)

Arguments

Returns

integer (opens new window) – The number of characters in $str.

# lineWrapAfterWord()

Since
3.3.0

Line wrap the string after $limit, but also after the next word.

View source (opens new window)

Arguments

Returns

string (opens new window) – The line wrapped string.

# lines()

Splits on newlines and carriage returns, returning an array of strings corresponding to the lines in the string.

View source (opens new window)

Arguments

Returns

string (opens new window)[] – An array of strings.

# lowercaseFirst()

Converts the first character of the supplied string to lower case.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with the first character converted to lowercase.

# pad()

Since
3.3.0

Pads the string to a given length with $padStr. If length is less than or equal to the length of the string, no padding takes places. The default string used for padding is a space, and the default type (one of 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException if $padType isn't one of those 3 values.

View source (opens new window)

Arguments

Returns

string (opens new window) – The padded string.

# padBoth()

Since
3.3.0

Returns a new string of a given length such that both sides of the string are padded. Alias for pad() with a $padType of 'both'.

View source (opens new window)

Arguments

Returns

string (opens new window) – The padded string.

# padLeft()

Since
3.3.0

Returns a new string of a given length such that the beginning of the string is padded. Alias for pad() with a $padType of 'left'.

View source (opens new window)

Arguments

Returns

string (opens new window) – The padded string.

# padRight()

Since
3.3.0

Returns a new string of a given length such that the end of the string is padded. Alias for pad() with a $padType of 'right'.

View source (opens new window)

Arguments

Returns

string (opens new window) – The padded string.

# prepend()

Returns a new string starting with $string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The full prepended string.

# randomString()

Generates a random string of latin alphanumeric characters that defaults to a $length of 36. If $extendedChars is set to true, additional symbols can be included in the string. Note that the generated string is not a cryptographically secure string. If you need a cryptographically secure string, use Craft::$app->security->generateRandomString() (opens new window).

View source (opens new window)

Arguments

Returns

string (opens new window) – The randomly generated string.

# randomStringWithChars()

Generates a random string of characters. Note that the generated string is not a cryptographically secure string. If you need a cryptographically secure string, use Craft::$app->security->generateRandomString() (opens new window).

View source (opens new window)

Arguments

Returns

string (opens new window) – The randomly generated string.

# regexReplace()

Replaces all occurrences of $pattern in $str by $replacement. An alias for mb_ereg_replace().

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the replacements.

# removeHtml()

Since
3.3.0

Remove html via "strip_tags()" from the string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with Html removed.

# removeHtmlBreak()

Since
3.3.0

Remove all breaks [
| \r\n | \r | \n | .

..] from the string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with Html breaks removed.

# removeLeft()

Returns a new string with the prefix $substring removed, if present.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string without the prefix $substring.

# removeRight()

Returns a new string with the suffix $substring removed, if present.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string without the suffix $substring.

# repeat()

Since
3.3.0

Returns a repeated string given a multiplier.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string without the suffix $substring.

# replace()

Replaces all occurrences of $search in $str by $replacement.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the replacements.

# replaceAll()

Since
3.3.0

Replaces all occurrences of $search in $str by $replacement.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the replacements.

# replaceBeginning()

Since
3.3.0

Replaces all occurrences of $search from the beginning of string with $replacement.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the replacements.

# replaceEnding()

Since
3.3.0

Replaces all occurrences of $search from the beginning of string with $replacement.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the replacements.

# replaceFirst()

Since
3.3.0

Replaces first occurrences of $search from the beginning of string with $replacement.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the replacements.

# replaceLast()

Since
3.3.0

Replaces last occurrences of $search from the ending of string with $replacement.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after the replacements.

# replaceMb4()

Since
3.1.13

Replaces 4-byte UTF-8 characters in a string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with converted 4-byte UTF-8 characters

Example

// Convert emojis to smilies
$string = StringHelper::replaceMb4($string, function($char) {
    switch ($char) {
        case '😀':
            return ':)';
        case '☹️':
            return ':(';
        default:
            return '¯\_(ツ)_/¯';
    }
});

# reverse()

Returns a reversed string. A multibyte version of strrev().

View source (opens new window)

Arguments

Returns

string (opens new window) – The reversed string.

# safeTruncate()

Since
3.3.0

Truncates the string to a given length, while ensuring that it does not split words. If $substring is provided, and truncating occurs, the string is further truncated so that the substring may be appended without exceeding the desired length.

View source (opens new window)

Arguments

Returns

string (opens new window) – The resulting string after truncating.

# shortenAfterWord()

Since
3.3.0

Shorten the string after $length, but also after the next word.

View source (opens new window)

Arguments

Returns

string (opens new window) – The shortened string.

# shuffle()

Since
3.3.0

Shorten the string after $length, but also after the next word.

View source (opens new window)

Arguments

Returns

string (opens new window) – The shortened string.

# slice()

Since
3.3.0

Returns the substring beginning at $start, and up to, but not including the index specified by $end. If $end is omitted, the function extracts the remaining string. If $end is negative, it is computed from the end of the string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The extracted substring.

# slugify()

Since
3.3.0

Converts the string into an URL slug. This includes replacing non-ASCII characters with their closest ASCII equivalents, removing remaining non-ASCII and non-alphanumeric characters, and replacing whitespace with $replacement. The replacement defaults to a single dash, and the string is also converted to lowercase. The language of the source string can also be supplied for language-specific transliteration.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string converted to a URL slug.

# split()

Since
3.3.0

Splits a string into chunks on a given delimiter.

View source (opens new window)

Arguments

Returns

string (opens new window)[] – The segments of the string.

# splitOnWords()

Splits a string into an array of the words in the string.

View source (opens new window)

Arguments

Returns

string (opens new window)[] – The words in the string

# startsWith()

Returns true if the string begins with $substring, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str starts with $substring.

# startsWithAny()

Since
3.3.0

Returns true if the string begins with any of $substrings, false otherwise.

By default the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether or not $str starts with $substring.

# stripCssMediaQueries()

Since
3.3.0

Remove CSS media-queries.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string, sans any CSS media queries.

# stripEmptyHtmlTags()

Since
3.3.0

Remove any empty HTML tags.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string, sans any empty HTML tags.

# stripHtml()

Since
3.3.0

Strips HTML tags out of a given string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string, sans-HTML

# stripWhitespace()

Since
3.3.0

Strip all whitespace characters. This includes tabs and newline characters, as well as multibyte whitespace such as the thin space and ideographic space.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string, sans-whitespace.

# substr()

Returns the substring beginning at $start with the specified|null $length. It differs from the mb_substr() function in that providing a|null $length of null will return the rest of the string, rather than an empty string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The substring of $str.

# substringOf()

Since
3.3.0

Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".

If no match is found, returns an empty string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The substring of $str.

# surround()

Since
3.3.0

Surrounds $str with the given substring.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with the substring both prepended and appended.

# swapCase()

Returns a case swapped version of the string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with each character's case swapped.

# tidy()

Since
3.3.0

Returns a string with smart quotes, ellipsis characters, and dashes from Windows-1252 (commonly used in Word documents) replaced by their ASCII equivalents.

View source (opens new window)

Arguments

Returns

string (opens new window) – The tidy string.

# titleize()

Returns a trimmed string with the first letter of each word capitalized. Ignores the case of other letters, preserving any acronyms. Also accepts an array, $ignore, allowing you to list words not to be capitalized.

View source (opens new window)

Arguments

Returns

string (opens new window) – The titleized string.

# titleizeForHumans()

Since
3.3.0

Returns a trimmed string in proper title case.

Also accepts an array, $ignore, allowing you to list words not to be capitalized.

Adapted from John Gruber's script.

See also https://gist.github.com/gruber/9f9e8650d68b13ce4d78 View source (opens new window)

Arguments

Returns

string (opens new window) – The titleized string.

# toAscii()

Returns an ASCII version of the string. A set of non-ASCII characters are replaced with their closest ASCII counterparts, and the rest are removed.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string that contains only ASCII characters.

# toBoolean()

Since
3.3.0

Returns a boolean representation of the given logical string value.

For example, 'true', '1', 'on' and 'yes' will return true. 'false', '0', 'off', and 'no' will return false. In all instances, case is ignored. For other numeric strings, their sign will determine the return value. In addition, blank strings consisting of only whitespace will return false. For all other strings, the return value is a result of a boolean cast.

View source (opens new window)

Arguments

Returns

boolean (opens new window) – A boolean value for the string.

# toCamelCase()

CamelCases a string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string camelized.

# toKebabCase()

Kebab-cases a string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The kebab-cased string.

# toLowerCase()

Converts all characters in the string to lowercase. An alias for PHP's mb_strtolower().

View source (opens new window)

Arguments

Returns

string (opens new window) – The lowercase string.

# toPascalCase()

PascalCases a string.

View source (opens new window)

Arguments

Returns

string (opens new window)

# toSnakeCase()

Snake_cases a string.

View source (opens new window)

Arguments

Returns

string (opens new window) – The snakeized string.

# toSpaces()

Since
3.3.0

Converts each tab in the string to some number of spaces, as defined by $tabLength. By default, each tab is converted to 4 consecutive spaces.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with tabs converted to spaces.

# toString()

Converts an object to its string representation. If the object is an array, will glue the array elements togeter with the $glue param. Otherwise will cast the object to a string.

View source (opens new window)

Arguments

  • $object (mixed) – The object to convert to a string.
  • $glue (string (opens new window)) – The glue to use if the object is an array.

Returns

string (opens new window) – The string representation of the object.

# toTabs()

Since
3.3.0

Converts each occurrence of some consecutive number of spaces, as defined by $tabLength, to a tab. By default, each 4 consecutive spaces are converted to a tab.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with spaces converted to tabs.

# toTitleCase()

Converts the first character of each word in the string to uppercase.

View source (opens new window)

Arguments

Returns

string (opens new window) – The title-cased string.

# toTransliterate()

Since
3.3.0

Returns an ASCII version of the string. A set of non-ASCII characters are replaced with their closest ASCII counterparts, and the rest are removed unless instructed otherwise.

View source (opens new window)

Arguments

Returns

string (opens new window) – The transliterated string.

# toUpperCase()

Converts all characters in the string to uppercase. An alias for PHP's mb_strtoupper().

View source (opens new window)

Arguments

Returns

string (opens new window) – The uppercase string.

# toWords()

Since
3.1.0

Returns an array of words extracted from a string

View source (opens new window)

Arguments

Returns

string (opens new window)[] – The prepped words in the string

# trim()

Returns a string with whitespace removed from the start and end of the string. Supports the removal of unicode whitespace. Accepts an optional string of characters to strip instead of the defaults.

View source (opens new window)

Arguments

Returns

string (opens new window) – The trimmed $str.

# trimLeft()

Since
3.3.0

Returns a string with whitespace removed from the start of the string.

Supports the removal of unicode whitespace. Accepts an optional string of characters to strip instead of the defaults.

View source (opens new window)

Arguments

Returns

string (opens new window) – The trimmed $str.

# trimRight()

Since
3.3.0

Returns a string with whitespace removed from the end of the string.

Supports the removal of unicode whitespace. Accepts an optional string of characters to strip instead of the defaults.

View source (opens new window)

Arguments

Returns

string (opens new window) – The trimmed $str.

# upperCamelize()

Since
3.3.0

Returns an UpperCamelCase version of the supplied string. It trims surrounding spaces, capitalizes letters following digits, spaces, dashes and underscores, and removes spaces, dashes, underscores.

View source (opens new window)

Arguments

Returns

string (opens new window) – The upper camelized $str.

# upperCaseFirst()

Since
3.3.0

Converts the first character of the supplied string to uppercase.

View source (opens new window)

Arguments

Returns

string (opens new window) – The string with the first character being uppercase.

# Protected Methods

Method Description
truncateHtml() (opens new window) Truncate a string while preserving the HTML.

# Constants

Constant Description
UTF8
UUID_PATTERN