Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - add underscores before capital letters

Tags:

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

SomeText 

to

Some_Text 

?

like image 354
Alex Avatar asked Jun 03 '11 12:06

Alex


1 Answers

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]

like image 87
josef.van.niekerk Avatar answered Jan 05 '23 12:01

josef.van.niekerk