Search code examples
phpregexstringcase-conversion

PHP - add underscores before capital letters


How can I replace a set of words that look like:

SomeText

to

Some_Text

?


Solution

  • This can easily be achieved using a regular expression:

    $result = preg_replace('/\B([A-Z])/', '_$1', $subject);
    

    a brief explanation of the regex:

    • \B asserts position at a word boundary.
    • [A-Z] matches any uppercase characters from A-Z.
    • () wraps the match in a back reference number 1.

    Then we replace with '_$1' which means replace the match with an [underscore + backreference 1]