【发布时间】:2013-06-26 01:17:05
【问题描述】:
通过使用@ridgerunner 在此问题中建议的解决方案,我设法实现了一个将驼峰大小写转换为单词的功能:
Split camelCase word into words with php preg_match (Regular Expression)
但是,我还想处理这样的嵌入式缩写:
'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() 函数两次?
【问题讨论】:
-
当您通过连接和使用 PHP cmets 而不是正则表达式 cmets 来避免所有空格时,为什么要使用
x修饰符?x的漏洞在于您可以将表达式作为一个多行字符串传递,#...cmets. -
我不知道 \x 的含义。我从提到的来源复制了模式并从那里扩展。谢谢你的信息。
标签: php regex preg-split camelcasing