【发布时间】:2014-08-02 23:44:55
【问题描述】:
我有以下功能:
function dashesToCamelCase($string)
{
return str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
}
function camelCaseToDashes($string) {
//This method should not have Regex
$string = preg_replace('/\B([A-Z])/', '-$1', $string);
return strtolower($string);
}
这是一个测试:
$testArray = ['UserProfile', 'UserSettings', 'Settings', 'SuperLongString'];
foreach ($testArray as $testData) {
$dashed = camelCaseToDashes($testData);
$orignal = dashesToCamelCase($dashed);
echo '<pre>' . $dashed . ' | ' . $orignal . '</pre>';
}
这是预期的输出:
user-profile | UserProfile
user-settings | UserSettings
settings | Settings
super-long-string | SuperLongString
现在我的问题:方法camelCaseToDashes 现在正在使用Regex。你能想象没有Regex 的更好(更快)实现吗?
【问题讨论】:
-
这是一个过早的优化
-
Regex 实现已经使用可用的最佳内置函数进行了优化,甚至使用 C 代码编写为 PHP 模块的一些底层优化。你不需要重新发明轮子......
-
感谢@HenriqueBarcelos,只是认为这不是“常规问题”,因为很多人说:避免使用正则表达式。但是这个例子(以及相应的基准答案)让我大开眼界。