是否可以将驼峰式大小写字符串解析为更具可读性的内容。
例如:
更新
使用 simshaun 正则表达式示例,我设法使用此规则将数字与文本分开:
function parseCamelCase($str)
{
return preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]|[0-9]{1,}/', ' $0', $str);
}
//string(65) "customer ID With Some Other JET Words With Number 23rd Text After"
echo parseCamelCase('customerIDWithSomeOtherJETWordsWithNumber23rdTextAfter');
PHP手册中str_split的用户注释中有一些示例。
来自凯文:
<?php
$test = 'CustomerIDWithSomeOtherJETWords';
preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', ' $0', $test);
这是我为满足您的帖子要求而写的内容:
<?php
$tests = array(
'LocalBusiness' => 'Local Business',
'CivicStructureBuilding' => 'Civic Structure Building',
'getUserMobilePhoneNumber' => 'Get User Mobile Phone Number',
'bandGuitar1' => 'Band Guitar 1',
'band2Guitar123' => 'Band 2 Guitar 123',
);
foreach ($tests AS $input => $expected) {
$output = preg_replace(array('/(?<=[^A-Z])([A-Z])/', '/(?<=[^0-9])([0-9])/'), ' $0', $input);
$output = ucwords($output);
echo $output .' : '. ($output == $expected ? 'PASSED' : 'FAILED') .'<br>';
}
这是我尝试将 PascalCase 和 CamelCase 字符串解析为空格分隔的标题大小写的看法。模式内注释应该有助于描述每个子模式正在做什么。
代码:(演示)
$tests = [
'LocalBusiness' => 'Local Business',
'CivicStructureBuilding' => 'Civic Structure Building',
'getUserMobilePhoneNumber' => 'Get User Mobile Phone Number',
'bandGuitar1' => 'Band Guitar 1',
'band2Guitar123' => 'Band 2 Guitar 123',
'CustomerIDWithSomeOtherJETWords' => 'Customer ID With Some Other JET Words',
'noOneIsMightierThanI' => 'No One Is Mightier Than I',
'USAIsNumber14' => 'USA Is Number 14',
'99LuftBallons' => '99 Luft Ballons',
];
$result = [];
foreach ($tests as $input => $expected) {
$newString = ucwords(
preg_replace(
'/(?:
[A-Z]+? (?=\d|[A-Z][a-z]) #acronyms
|[A-Z]?[a-z]+ (?=[^a-z]) #words
|\d+ (?=\D) #numbers
|(*SKIP)(*FAIL) #abort
)\K
/x',
' ',
$input
)
);
$result[] = ($newString === $expected ? 'PASSED' : 'FAILED') . ': "' . $newString . '"';
}
var_export($result);
acronyms
通过匹配 1 个或多个大写字母后跟数字或单词来找到。words
通过匹配小写字母来找到,这些字母前面可能有也可能没有大写字母。numbers
通过匹配 1 个或多个数字后跟一个非数字来找到。