Skip to content

StringHelper

Type
Class
Namespace
craft\helpers
Inherits
craft\helpers\StringHelper » yii\helpers\StringHelper » yii\helpers\BaseStringHelper
Since
3.0.0

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

View source

Public Methods

MethodDescription
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 config setting.
at()Returns the character at $index, with indexes starting at 0.
base64UrlDecode()Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
base64UrlEncode()Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
basename()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()Returns the number of bytes in the given string.
byteSubstr()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()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()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()Check if given string ends with specified substring. Binary and multibyte safe.
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()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()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()Checks if the passed string would match the given shell wildcard pattern.
mb_ucfirst()This method provides a unicode-safe implementation of built-in PHP function ucfirst().
mb_ucwords()This method provides a unicode-safe implementation of built-in PHP function ucwords().
normalizeNumber()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().
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().
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 together 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()Truncates a string to the number of characters specified.
truncateWords()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

Returns

string – The UUID.

Throws

afterFirst()

Since
3.3.0

Gets the substring after the first occurrence of a separator.

View source

Arguments

  • $str (string) – The string to search.
  • $separator (string) – The separator string.
  • $caseSensitive (boolean) – Whether or not to enforce case-sensitivity.

Returns

string – The resulting string.

afterLast()

Since
3.3.0

Gets the substring after the last occurrence of a separator.

View source

Arguments

  • $str (string) – The string to search.
  • $separator (string) – The separator string.
  • $caseSensitive (boolean) – Whether or not to enforce case-sensitivity.

Returns

string – The resulting string.

append()

Since
3.3.0

Returns a new string with $append appended.

View source

Arguments

  • $str (string) – The initial un-appended string.
  • $append (string) – The string to append.

Returns

string – The newly appended string.

appendRandomString()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The initial un-appended string.
  • $length (integer) – The length of the random string.
  • $possibleChars (string) – The possible random characters to append.

Returns

string – The newly appended string.

appendUniqueIdentifier()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The initial un-appended string.
  • $entropyExtra (string) – Extra entropy via a string or int value.
  • $md5 (boolean) – Whether or not to return the unique identifier as a md5 hash.

Returns

string – The newly appended string.

asciiCharMap()

Returns ASCII character mappings, merging in any custom defined mappings from the config3:customAsciiCharMappings config setting.

View source

Arguments

  • $flat (boolean) – Whether the mappings should be returned as a flat array (é => e)
  • $language (string, null) – Whether to include language-specific mappings (only applied if $flat is true)

Returns

array – The fully merged ASCII character mappings.

at()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The initial string to search.
  • $index (integer) – The position of the character.

Returns

string – The resulting character.

beforeFirst()

Since
3.3.0

Gets the substring before the first occurrence of a separator.

View source

Arguments

  • $str (string) – The string to search.
  • $separator (string) – The separator string.
  • $caseSensitive (boolean)

Returns

string – The resulting string.

beforeLast()

Since
3.3.0

Gets the substring before the last occurrence of a separator.

View source

Arguments

  • $str (string) – The string to search.
  • $separator (string) – The separator string.
  • $caseSensitive (boolean)

Returns

string – 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

Arguments

  • $str (string) – The string to search.
  • $start (string) – Delimiter marking the start of the substring.
  • $end (string) – Delimiter marking the end of the substring.
  • $offset (integer, null) – Index from which to begin the search. Defaults to 0.

Returns

string – 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

Arguments

  • $str (string) – The string to convert to camelCase.

Returns

string – 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

Arguments

  • $str (string) – The string to parse.

Returns

string – The string with personal names capitalized.

charsAsArray()

Returns an array consisting of the characters in the string.

View source

Arguments

Returns

string[] – 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

Arguments

  • $str (string) – The string to remove the whitespace from.

Returns

string – 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

Arguments

  • $haystack (string) – The string being checked.
  • $needle (string) – The substring to look for.
  • $caseSensitive (boolean) – Whether or not to force case-sensitivity.

Returns

boolean – 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

Arguments

  • $haystack (string) – The string being checked.
  • $needles (array) – The substrings to look for.
  • $caseSensitive (boolean) – Whether or not to force case-sensitivity.

Returns

boolean – 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

Arguments

  • $haystack (string) – The string being checked.
  • $needles (array) – The substrings to look for.
  • $caseSensitive (boolean) – Whether or not to force case-sensitivity.

Returns

boolean – Whether or not $haystack contains any $needles.

containsMb4()

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

View source

Arguments

  • $str (string) – The string to process.

Returns

boolean – 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

Arguments

Returns

string

count()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The string to count.

Returns

integer – 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

Arguments

  • $str (string) – The string to search through.
  • $substring (string) – The substring to search for.
  • $caseSensitive (boolean) – Whether or not to enforce case-sensitivity

Returns

integer – 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

Arguments

  • $str (string) – The string to dasherize.

Returns

string – The dasherized string.

decdec()

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

View source

Arguments

Returns

string

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

Arguments

  • $str (string) – The string to delimit.
  • $delimiter (string) – Sequence used to separate parts of the string

Returns

string – The delimited string.

encenc()

Encrypts and base64-encodes a string.

See also decdec()View source

Arguments

Returns

string

Throws

encodeMb4()

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

See also http://stackoverflow.com/a/16496730/1688568View source

Arguments

Returns

string – The string with converted 4-byte UTF-8 characters

encoding()

Gets the encoding of the given string.

View source

Arguments

  • $str (string) – The string to process.

Returns

string – 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

Arguments

  • $str (string) – The string to check the end of.
  • $substrings (mixed) – [] Substrings to look for.
  • $caseSensitive (boolean) – Whether or not to force case-sensitivity.

Returns

boolean – Whether or not $str ends with $substring.

ensureLeft()

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

View source

Arguments

  • $str (string) – The string to modify.
  • $substring (string) – The substring to add if not present.

Returns

string – The string prefixed by the $substring.

ensureRight()

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

View source

Arguments

  • $str (string) – The string to modify.
  • $substring (string) – The substring to add if not present.

Returns

string – 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

Arguments

  • $str (string) – The string to modify.

Returns

string – 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

Arguments

  • $str (string) – The source string.
  • $search (string) – The string to search for.
  • $length (integer, null) – By default, the length of the text divided by two.
  • $replacerForSkippedText (string) – The string to use for skipped text.

Returns

string – The string to escape.

first()

Returns the first $n characters of the string.

View source

Arguments

  • $str (string) – The string from which to get the substring.
  • $number (integer) – The Number of chars to retrieve from the start.

Returns

string – The first $number characters.

hasLowerCase()

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

View source

Arguments

  • $str (string) – The string to check.

Returns

boolean – If the string has a lowercase character or not.

hasUpperCase()

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

View source

Arguments

  • $str (string) – The string to check.

Returns

boolean – If the string has an uppercase character or not.

htmlDecode()

Since
3.3.0

Convert all HTML entities to their applicable characters.

View source

Arguments

Returns

string – The decoded string.

htmlEncode()

Since
3.3.0

Convert all applicable characters to HTML entities.

View source

Arguments

Returns

string – The encoded string.

humanize()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The string to process.

Returns

string – The humanized string.

idnToUtf8Email()

Since
3.5.16

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

View source

Arguments

Returns

string

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

Arguments

  • $str (string) – The string to check the index of.
  • $needle (string) – The substring to look for.
  • $offset (integer) – The offset from which to search.
  • $caseSensitive (boolean) – Whether to perform a case-sensitive search or not.

Returns

integer, boolean – 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

Arguments

  • $str (string) – The string to check the last index of.
  • $needle (string) – The substring to look for.
  • $offset (integer) – The offset from which to search.
  • $caseSensitive (boolean) – Whether to perform a case-sensitive search or not.

Returns

integer, boolean – The occurrence's last index if found, otherwise false.

insert()

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

View source

Arguments

  • $str (string) – The string to insert into.
  • $substring (string) – The string to be inserted.
  • $index (integer) – The 0-based index at which to insert the substring.

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $pattern (string) – The string or pattern to match against.

Returns

boolean – Whether or not we match the provided pattern.

isAlpha()

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

View source

Arguments

  • $str (string) – The string to check.

Returns

boolean – Whether or not $str contains only alphabetic chars.

isAlphanumeric()

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

View source

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.
  • $emptyStringIsValid (boolean) – Whether or not an empty string is considered valid.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.
  • $onlyArrayOrObjectResultsAreValid (boolean)

Returns

boolean – Whether or not $str is JSON.

isLowerCase()

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

View source

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $uuid (string) – The string to check.

Returns

boolean – Whether the string matches a v4 UUID pattern.

isUpperCase()

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

View source

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check.

Returns

boolean – Whether or not $str contains only whitespace characters.

last()

Returns the last $number characters of the string.

View source

Arguments

  • $str (string) – The string from which to get the substring.
  • $number (integer) – The Number of chars to retrieve from the end.

Returns

string – The last $number characters.

lastSubstringOf()

Since
3.3.0

Returns the last $number characters of the string.

View source

Arguments

  • $str (string) – The string from which to get the substring.
  • $needle (string) – The substring to look for.
  • $beforeNeedle (boolean)
  • $caseSensetive (boolean) – Whether or not to perform a case sensitive search.

Returns

string – The last $number characters.

length()

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

View source

Arguments

  • $str (string) – The string to get the length of.

Returns

integer – 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

Arguments

  • $str (string) – The string to process.
  • $limit (integer) – The number of characters to insert the line wrap.

Returns

string – 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

Arguments

  • $str (string) – The string to split.

Returns

string[] – An array of strings.

lowercaseFirst()

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

View source

Arguments

  • $str (string) – The string to modify.

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $length (integer) – The desired length after padding.
  • $padStr (string) – The string used to pad. Defaults to space.
  • $padType (string) – 'left', 'right', 'both'. Defaults to 'right'.

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $length (integer) – The desired length after padding.
  • $padStr (string) – The string used to pad. Defaults to space.

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $length (integer) – The desired length after padding.
  • $padStr (string) – The string used to pad. Defaults to space.

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $length (integer) – The desired length after padding.
  • $padStr (string) – The string used to pad. Defaults to space.

Returns

string – The padded string.

prepend()

Returns a new string starting with $string.

View source

Arguments

  • $str (string) – The string to process.
  • $string (string) – The string to prepend.

Returns

string – 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().

View source

Arguments

  • $length (integer) – The length of the random string. Defaults to 36.
  • $extendedChars (boolean) – Whether to include symbols in the random string.

Returns

string – 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().

View source

Arguments

  • $validChars (string) – A string containing the valid characters
  • $length (integer) – The length of the random string

Returns

string – The randomly generated string.

regexReplace()

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

View source

Arguments

  • $str (string) – The haystack to search through.
  • $pattern (string) – The regular expression pattern.
  • $replacement (string) – The string to replace with.
  • $options (string) – Matching conditions to be used. Defaults to 'msr'. See here for all options.

Returns

string – The resulting string after the replacements.

removeHtml()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The string to process.
  • $allowableTags (string, null) – Tags that should not be stripped.

Returns

string – The string with Html removed.

removeHtmlBreak()

Since
3.3.0

Remove all breaks [
| \r\n | \r | \n | ...] from the string.

View source

Arguments

  • $str (string) – The string to process.
  • $replacement (string) – The optional string to replace with.

Returns

string – The string with Html breaks removed.

removeLeft()

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

View source

Arguments

  • $str (string) – The string from which to remove the prefix.
  • $substring (string) – The prefix to remove.

Returns

string – The string without the prefix $substring.

removeRight()

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

View source

Arguments

  • $str (string) – The string from which to remove the suffix.
  • $substring (string) – The suffix to remove.

Returns

string – The string without the suffix $substring.

repeat()

Since
3.3.0

Returns a repeated string given a multiplier.

View source

Arguments

  • $str (string) – The string to process.
  • $multiplier (integer) – The number of times to repeat the string.

Returns

string – The string without the suffix $substring.

replace()

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

View source

Arguments

  • $str (string) – The haystack to search through.
  • $search (string) – The needle to search for.
  • $replacement (string) – The string to replace with.

Returns

string – The resulting string after the replacements.

replaceAll()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The haystack to search through.
  • $search (array) – The needle(s) to search for.
  • $replacement (array, string) – The string(s) to replace with.
  • $caseSensitive (boolean) – Whether or not to perform a case-sensitive search.

Returns

string – 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

Arguments

  • $str (string) – The haystack to search through.
  • $search (string) – The needle to search for.
  • $replacement (string) – The string to replace with.

Returns

string – 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

Arguments

  • $str (string) – The haystack to search through.
  • $search (string) – The needle to search for.
  • $replacement (string) – The string to replace with.

Returns

string – 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

Arguments

  • $str (string) – The haystack to search through.
  • $search (string) – The needle to search for.
  • $replacement (string) – The string to replace with.

Returns

string – 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

Arguments

  • $str (string) – The haystack to search through.
  • $search (string) – The needle to search for.
  • $replacement (string) – The string to replace with.

Returns

string – The resulting string after the replacements.

replaceMb4()

Since
3.1.13

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

View source

Arguments

  • $str (string) – The string
  • $replace (string, callable) – The replacement string, or callback function.

Returns

string – The string with converted 4-byte UTF-8 characters


Example

php
// 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

Arguments

  • $str (string) – The string to reverse.

Returns

string – 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

Arguments

  • $str (string) – The string to truncate.
  • $length (integer) – The desired length of the truncated string.
  • $substring (string) – The substring to append if it can fit.
  • $ignoreDoNotSplitWordsForOneWord (boolean)

Returns

string – The resulting string after truncating.

shortenAfterWord()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The string to process
  • $length (integer) – The length to start the shortening.
  • $strAddOn (string) – The character to use after the length.

Returns

string – The shortened string.

shuffle()

Since
3.3.0

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

View source

Arguments

  • $str (string) – The string to process

Returns

string – 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

Arguments

  • $str (string) – The string to process
  • $start (integer) – Index from which to begin the extraction.
  • $end (integer, null) – Index at which to end the extraction.

Returns

string – 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

Arguments

  • $str (string) – The string to process
  • $replacement (string) – The string used to replace whitespace.
  • $language (string, null) – The language of the source string.

Returns

string – The string converted to a URL slug.

split()

Since
3.3.0

Splits a string into chunks on a given delimiter.

View source

Arguments

  • $str (string) – The string
  • $delimiter (string) – The delimiter to split the string on (defaults to a comma)

Returns

string[] – The segments of the string.

splitOnWords()

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

View source

Arguments

Returns

string[] – 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

Arguments

  • $str (string) – The string to check the start of.
  • $substring (string) – The substring to look for.
  • $caseSensitive (boolean) – Whether or not to enforce case-sensitivity.

Returns

boolean – 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

Arguments

  • $str (string) – The string to check the start of.
  • $substrings (array) – The substrings to look for.
  • $caseSensitive (boolean) – Whether or not to enforce case-sensitivity.

Returns

boolean – Whether or not $str starts with $substring.

stripCssMediaQueries()

Since
3.3.0

Remove CSS media-queries.

View source

Arguments

  • $str (string) – The string to process.

Returns

string – The string, sans any CSS media queries.

stripEmptyHtmlTags()

Since
3.3.0

Remove any empty HTML tags.

View source

Arguments

  • $str (string) – The string to process.

Returns

string – The string, sans any empty HTML tags.

stripHtml()

Since
3.3.0

Strips HTML tags out of a given string.

View source

Arguments

Returns

string – 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

Arguments

Returns

string – 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

Arguments

  • $str (string) – The string to get the length of.
  • $start (integer) – Position of the first character to use.
  • $length (integer, null) – Maximum number of characters used.

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $needle (string) – The string to look for.
  • $beforeNeedle (boolean)
  • $caseSensitive (boolean) – Whether to perform a case-sensitive search or not.

Returns

string – The substring of $str.

surround()

Since
3.3.0

Surrounds $str with the given substring.

View source

Arguments

  • $str (string) – The string to process.
  • $substring (string) – The substring to add to both sides.

Returns

string – The string with the substring both prepended and appended.

swapCase()

Returns a case swapped version of the string.

View source

Arguments

  • $str (string) – The string to swap case.

Returns

string – 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

Arguments

  • $str (string) – The string to tidy.

Returns

string – 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

Arguments

  • $str (string) – The string to titleize.
  • $ignore (array, null) – An array of words not to capitalize.

Returns

string – 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/9f9e8650d68b13ce4d78View source

Arguments

  • $str (string) – The string to titleize.
  • $ignore (array) – An array of words not to capitalize.

Returns

string – 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

Arguments

  • $str (string) – The string to convert.
  • $language (string, null) – The language to pull ASCII character mappings for.

Returns

string – 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

Arguments

  • $str (string) – The string to process.

Returns

boolean – A boolean value for the string.

toCamelCase()

CamelCases a string.

View source

Arguments

  • $str (string) – The string to camelize.

Returns

string – The string camelized.

toKebabCase()

Kebab-cases a string.

View source

Arguments

  • $str (string) – The string the process.
  • $glue (string) – The string used to glue the words together (default is a hyphen)
  • $lower (boolean) – Whether the string should be lowercased (default is true)
  • $removePunctuation (boolean) – Whether punctuation marks should be removed (default is true)

Returns

string – The kebab-cased string.

toLowerCase()

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

View source

Arguments

  • $str (string) – The string to convert to lowercase.

Returns

string – The lowercase string.

toPascalCase()

PascalCases a string.

View source

Arguments

  • $str (string) – The string to process.

Returns

string

toSnakeCase()

Snake_cases a string.

View source

Arguments

  • $str (string) – The string to snakeize.

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $tabLength (integer) – The number of spaces to replace each tab with. Defaults to four.

Returns

string – 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 together with the $glue param. Otherwise will cast the object to a string.

View source

Arguments

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

Returns

string – 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

Arguments

  • $str (string) – The string to process.
  • $tabLength (integer) – The number of spaces to replace with a tab. Defaults to four.

Returns

string – The string with spaces converted to tabs.

toTitleCase()

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

View source

Arguments

  • $str (string) – The string to convert case.

Returns

string – 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

Arguments

  • $str (string) – The string to transliterate.
  • $strict (boolean) – Use "transliterator_transliterate()" from the PHP intl extension.

Returns

string – The transliterated string.

toUpperCase()

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

View source

Arguments

  • $str (string) – The string to convert to uppercase.

Returns

string – The uppercase string.

toWords()

Since
3.1.0

Returns an array of words extracted from a string

View source

Arguments

  • $str (string) – The string
  • $lower (boolean) – Whether the returned words should be lowercased
  • $removePunctuation (boolean) – Whether punctuation should be removed from the returned words

Returns

string[] – 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

Arguments

  • $str (string) – The string to trim.
  • $chars (string, null) – String of characters to strip. Defaults to null.

Returns

string – 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

Arguments

  • $str (string) – The string to trim.
  • $chars (string, null) – String of characters to strip. Defaults to null.

Returns

string – 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

Arguments

  • $str (string) – The string to trim.
  • $chars (string, null) – String of characters to strip. Defaults to null.

Returns

string – 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

Arguments

  • $str (string) – The string to upper camelize.

Returns

string – The upper camelized $str.

upperCaseFirst()

Since
3.3.0

Converts the first character of the supplied string to uppercase.

View source

Arguments

  • $str (string) – The string to modify.

Returns

string – The string with the first character being uppercase.

Protected Methods

MethodDescription
truncateHtml()Truncate a string while preserving the HTML.

Constants

ConstantDescription
UTF8
UUID_PATTERN