PHP - add underscores before capital letters

前端 未结 5 2297
梦如初夏
梦如初夏 2021-02-18 14:48

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

SomeText

to

Some_Text

?

5条回答
  •  梦如初夏
    2021-02-18 15:38

    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]

提交回复
热议问题