3

i'm working on class names and i need to check if there is any upper camel case name and break it this way:

 "UserManagement" becomes "user-management"  

or

 "SiteContentManagement" becomes "site-content-management"

after extensive search i only found various use of ucfirst, strtolower,strtoupper, ucword and i can't see how to use them to suit my needs any ideas?

thanks for reading ;)

black sensei
  • 6,528
  • 22
  • 109
  • 188
  • Try these: http://stackoverflow.com/questions/4211875/check-if-a-string-is-all-caps-in-php http://stackoverflow.com/questions/1182013/php-count-uppercase-words-in-string http://stackoverflow.com/questions/2814880/how-to-check-if-letter-is-upper-or-lower-in-php – random Jul 03 '11 at 19:00

5 Answers5

5

You can use preg_replace to replace any instance of a lowercase letter followed with an uppercase with your lower-dash-lower variant:

$dashedName = preg_replace('/([^A-Z-])([A-Z])/', '$1-$2', $className);

Then followed by a strtolower() to take care of any remaining uppercase letters:

return strtolower($dashedName);

The full function here:

function camel2dashed($className) {
  return strtolower(preg_replace('/([^A-Z-])([A-Z])/', '$1-$2', $className));
}

To explain the regular expression used:

/        Opening delimiter
(        Start Capture Group 1
  [^A-Z-]   Character Class: Any character NOT an uppercase letter and not a dash
)        End Capture Group 1
(        Start Capture Group 2
  [A-Z]    Character Class: Any uppercase letter
)        End Capture Group 2
/        Closing delimiter

As for the replacement string

$1  Insert Capture Group 1
-   Literal: dash
$2  Insert Capture Group 2
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
3

Theres no built in way to do it.

This will ConvertThis into convert-this:

$str = preg_replace('/([a-z])([A-Z])/', '$1-$2', $str);
$str = strtolower($str);
Glass Robot
  • 2,438
  • 19
  • 11
2

You can use a regex to get each words, then add the dashes like this:

preg_match_all ('/[A-Z][a-z]+/', $className, $matches); // get each camelCase words
$newName = strtolower(implode('-', $matches[0])); // add the dashes and lowercase the result
Martin Larente
  • 510
  • 2
  • 9
0

This simply done without any capture groups -- just find the zero-width position before an uppercase letter (excluding the first letter of the string), then replace it with a hyphen, then call strtolower on the new string.

Code: (Demo)

echo strtolower(preg_replace('~(?!^)(?=[A-Z])~', '-', $string));

The lookahead (?=...) makes the match but doesn't consume any characters.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
-1

The best way to do that might be preg_replace using a pattern that replaces uppercase letters with their lowercase counterparts adding a "-" before them.

You could also go through each letter and rebuild the whole string.

Kazuo
  • 387
  • 5
  • 12