通过使用@ridgerunner 在这个问题中建议的解决方案,我设法实现了一个将驼峰大小写转换为单词的函数:
使用php preg_match(正则表达式)将camelCase单词拆分为单词
但是,我还想处理这样的嵌入式缩写:
'hasABREVIATIONEmbedded' 转换为 'Has ABREVIATION Embedded'
我想出了这个解决方案:
<?php
function camelCaseToWords($camelCaseStr)
{
// Convert: "TestASAPTestMore" to "TestASAP TestMore"
$abreviationsPattern = '/' . // Match position between UPPERCASE "words"
'(?<=[A-Z])' . // Position is after group of uppercase,
'(?=[A-Z][a-z])' . // and before group of lowercase letters, except the last upper case letter in the group.
'/x';
$arr = preg_split($abreviationsPattern, $camelCaseStr);
$str = implode(' ', $arr);
// Convert "TestASAP TestMore" to "Test ASAP Test More"
$camelCasePattern = '/' . // Match position between camelCase "words".
'(?<=[a-z])' . // Position is after a lowercase,
'(?=[A-Z])' . // and before an uppercase letter.
'/x';
$arr = preg_split($camelCasePattern, $str);
$str = implode(' ', $arr);
$str = ucfirst(trim($str));
return $str;
}
$inputs = array(
'oneTwoThreeFour',
'StartsWithCap',
'hasConsecutiveCAPS',
'ALLCAPS',
'ALL_CAPS_AND_UNDERSCORES',
'hasABREVIATIONEmbedded',
);
echo "INPUT";
foreach($inputs as $val) {
echo "'" . $val . "' translates to '" . camelCaseToWords($val). "'\n";
}
输出是:
INPUT'oneTwoThreeFour' translates to 'One Two Three Four'
'StartsWithCap' translates to 'Starts With Cap'
'hasConsecutiveCAPS' translates to 'Has Consecutive CAPS'
'ALLCAPS' translates to 'ALLCAPS'
'ALL_CAPS_AND_UNDERSCORES' translates to 'ALL_CAPS_AND_UNDERSCORES'
'hasABREVIATIONEmbedded' translates to 'Has ABREVIATION Embedded'
它按预期工作。
我的问题是:我可以结合 2 个正则表达式 $abreviationsPattern 和 camelCasePattern 来避免运行 preg_split() 函数两次吗?