StringHelper

Type
Class
Namespace
craft\helpers
Inherits
craft\helpers\StringHelper » yii\helpers\StringHelper » yii\helpers\BaseStringHelper
Since
3.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]
asciiCharMap()Returns ASCII character mappings, merging in any custom defined mappings from the customAsciiCharMappings config setting.
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.
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.
charAt()Returns the character at a specific point in a potentially multibyte string.
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.
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.
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 current encoding of the given string.
endsWith()Returns true if the string ends with $substring, false otherwise. By default, the comparison is case-sensitive, but can be made insensitive by setting $caseSensitive to false.
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.
explode()Explodes string into array, optionally trims values and skips empty ones.
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.
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.
insert()Inserts $substring into the string at the $index provided.
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.
isHexadecimal()Returns true if the string contains only hexadecimal chars, false otherwise.
isLowerCase()Returns true if the string contains only lowercase chars, false otherwise.
isUUID()Returns is the given string matches a v4 UUID pattern.
isUpperCase()Returns true if the string contains only uppercase 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.
length()Returns the length of the string. An alias for PHP's mb_strlen() function.
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.
padBoth()Returns a new string of a given length such that both sides of the string are padded.
padLeft()Returns a new string of a given length such that the beginning of the string is padded.
padRight()Returns a new string of a given length such that the end of the string is padded.
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().
removeLeft()Returns a new string with the prefix $substring removed, if present.
removeRight()Returns a new string with the suffix $substring removed, if present.
replace()Replaces all occurrences of $search in $str by $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 t he desired length.
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.
stripHtml()Strips HTML tags out of a given string.
substr()Returns the substring beginning at $start with the specified
swapCase()Returns a case swapped version of the 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.
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.
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.
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.
toTitleCase()Converts the first character of each word in the string to uppercase.
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 the trimmed string. An alias for PHP's trim() function.
truncate()Truncates a string to the number of characters specified.
truncateWords()Truncates a string to the number of words specified.
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.

asciiCharMap()

Returns ASCII character mappings, merging in any custom defined mappings from the 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.

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.

charAt()

Returns the character at a specific point in a potentially multibyte string.

View source

Arguments

  • $str (string) – The string to check.
  • $i (integer) – The 0-offset position in the string to check.

Returns

string

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

Returns

boolean

convertToUtf8()

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

View source

Arguments

Returns

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.

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/1688568 View source

Arguments

  • $string (string) – The string

Returns

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

encoding()

Gets the current encoding of the given string.

View source

Arguments

Returns

string

endsWith()

Returns true if the string ends 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 end of.
  • $substring (string) – The substring 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.

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

hasUpperCase()

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

View source

Arguments

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

Returns

boolean

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.

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.

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

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.

isHexadecimal()

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 characters

isLowerCase()

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

View source

Arguments

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

Returns

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

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 uppercase chars, false otherwise.

View source

Arguments

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

Returns

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

isUtf8()

Checks if the given string is UTF-8 encoded.

View source

Arguments

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

Returns

boolean

isWhitespace()

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.

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.

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.

padBoth()

Returns a new string of a given length such that both sides of the string are padded.

View source

Arguments

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

Returns

string – The padded string.

padLeft()

Returns a new string of a given length such that the beginning of the string is padded.

View source

Arguments

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

Returns

string – The padded string.

padRight()

Returns a new string of a given length such that the end of the string is padded.

View source

Arguments

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

Returns

string – The padded 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.

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.

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.

replaceMb4()

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

View source

Arguments

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

Returns

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

Example

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()

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 t he 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.

Returns

string – The resulting string after truncating.

split()

Splits a string into chunks on a given delimiter.

View source

Arguments

  • $string (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

  • $string (string) – The string

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.

stripHtml()

Strips HTML tags out of a given string.

View source

Arguments

Returns

string – The string, sans-HTML

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.

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.

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.

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.

toCamelCase()

CamelCases a string.

See also:

View source

Arguments

  • $string (string) – The string

Returns

string

toKebabCase()

Kebab-cases a string.

See also:

View source

Arguments

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

See also:

View source

Arguments

  • $string (string) – The string

Returns

string

toSnakeCase()

Snake_cases a string.

See also:

View source

Arguments

  • $string (string) – The string

Returns

string

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

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.

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.

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()

Returns an array of words extracted from a string

See also:

View source

Arguments

  • $string (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 the trimmed string. An alias for PHP's trim() function.

View source

Arguments

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

Returns

string – The trimmed $str.

upperCaseFirst()

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