开发者

PHP: How to convert a string that contains upper case characters

i'm working on class names and i need to check if there is any upper camel case name and break it th开发者_JAVA百科is 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 ;)


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


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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜