PHP - add underscores before capital letters

Alex picture Alex · Jun 3, 2011 · Viewed 10.2k times · Source

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

SomeText

to

Some_Text

?

Answer

josef.van.niekerk picture josef.van.niekerk · Jun 3, 2011

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]