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:

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