Regular Expressions 101

Community Patterns

camelCase -> snake_case

1

Regular Expression
PCRE2 (PHP >=7.3)

/
(\b(?'first_word'[a-z](?!([[:alnum:]]*_)(?# the word doesn't contain underscores))(?:[a-z0-9]*)))|(\G(?'trailing_word'[A-Z][a-z0-9]*))
/
gm

Description

Works with many forms of alphanumeric camelCase

  • camelCase
  • camel
  • camelCaseCaseCase... (with as many words as you want)
  • ca65melCase (ca65mel_case)
  • camelCCase (camel_c_case)

What isn't matched

  • PascalCase
  • words with '_' underscores in them (camel_Snake_Case)

Remarks

  • all 'lowercase' words are matched... but they're not changed by the regex !
Submitted by inesvar - a month ago