camelCase to dash - 彼此相邻的两个首都

时间:2022-06-07 09:01:58

I'm using this function to convert CamelCase to dashed string:

我正在使用此函数将CamelCase转换为虚线字符串:

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

it kinda works but theres problem when I have for ex. this string: getADog. It returns get-adog but I want get-a-dog

它有点工作但是当我有前任时有问题。这个字符串:getADog。它返回get-adog,但我想要得到一只狗

how should I change my code? Thanks

我应该如何更改我的代码?谢谢

2 个解决方案

#1


28  

Use a lookahead assertion:

使用先行断言:

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

See it working online: ideone

看它在线工作:ideone

#2


6  

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

这仍然不会处理像@ sfjedi的“companyHQ” - >“company-hq”这样的情况。为此,您必须明确测试不应拆分的允许的大写子串,或指定一些通用规则(例如,不要在最后一个字符之前添加连字符)。

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

您可以在此虚拟重复问题的答案中找到一些更复杂的替代方案。

#1


28  

Use a lookahead assertion:

使用先行断言:

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

See it working online: ideone

看它在线工作:ideone

#2


6  

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

这仍然不会处理像@ sfjedi的“companyHQ” - >“company-hq”这样的情况。为此,您必须明确测试不应拆分的允许的大写子串,或指定一些通用规则(例如,不要在最后一个字符之前添加连字符)。

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

您可以在此虚拟重复问题的答案中找到一些更复杂的替代方案。