camelCase to dash - two capitals next to each other

拈花ヽ惹草 提交于 2019-11-30 18:31:06

Use a lookahead assertion:

function camel2dashed($className) {
    return strtolower(preg_replace('/([a-zA-Z])(?=[A-Z])/', '$1-', $className));
}

See it working online: ideone

Ergwun

You don't need a lookahead assertion to do this if you know that your string doesn't start with an upper-case letter, you can just insert a hyphen before every upper-case letter like this:

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

This still won't handle cases like @sfjedi's "companyHQ" -> "company-hq". For that you'd have to explicitly test for permitted capitalized substrings that shouldn't be split, or specify some generic rules (e.g. don't prepend hyphen before last character).

You can find some more sophisticated alternatives in the answers to this virtual duplicate question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!