Converts strings between snake_case, camelCase, PascalCase and kebab-case. All four methods share one tokenizer, so any input style can be converted to any output style. The tokenizer splits on:
- runs of characters that are not letters, digits or combining marks (space,
_,-,., ...); leading and trailing separators are ignored; - case boundaries: lower case or digit followed by upper case (
firstName), and an acronym followed by a capitalised word (HTTPServergiveshttp,server).
Digits stay attached to the preceding word (userID2Name gives user, id2, name). Matching is
Unicode-aware, and an empty string converts to an empty string.
public static function toSnakeCase(string $string): stringStringUtil::toSnakeCase('Email-Address'); // 'email_address'
StringUtil::toSnakeCase('HTTPServer'); // 'http_server'
StringUtil::toSnakeCase('userID2Name'); // 'user_id2_name'
StringUtil::toSnakeCase('élanVital'); // 'élan_vital'public static function toCamelCase(string $string): stringStringUtil::toCamelCase('LAST_NAME'); // 'lastName'
StringUtil::toCamelCase('first name'); // 'firstName'public static function toPascalCase(string $string): stringStringUtil::toPascalCase('first_name'); // 'FirstName'public static function toKebabCase(string $string): stringStringUtil::toKebabCase('first name'); // 'first-name'
StringUtil::toKebabCase('FirstName'); // 'first-name'- Characters without case (for example CJK) are never split or changed.
- The first letter of each word is title-cased, not upper-cased:
toPascalCase('ßeta')isSseta(notSSeta) andtoPascalCase('džemal')isDžemal(notDŽemal). - Separators are dropped wherever they occur, so meaningful prefixes are lost:
_idand$refconvert likeidandref, and__typenameliketypename. - Acronyms are normalised:
toCamelCase('userID')isuserIdandtoCamelCase('iOS')isiOs. - A lower-case plural after an acronym splits oddly:
toSnakeCase('MyURLs')ismy_ur_ls. - A zero-width joiner counts as a separator, so
toSnakeCase("a\u{200D}b")isa_b. - Applying the same conversion twice gives the same result as applying it once, with these exceptions:
- Single-letter words are lost by PascalCase and by camelCase after the first word.
toPascalCase('a_b')isAB, which is read back as the single wordab. - A word whose first letter has no single upper-case form merges with the previous word in
PascalCase and camelCase.
toCamelCase('x_džy')isxDžy; converting that again givesxdžy, becauseDžis title case and is not treated as a case boundary.
- Single-letter words are lost by PascalCase and by camelCase after the first word.
Every method throws \InvalidArgumentException when the string is not valid UTF-8.