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 ;)

1

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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

Comments

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.

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.