如何将驼峰式大小写解析为人类可读的字符串?

问题描述 投票:0回答:2

是否可以将驼峰式大小写字符串解析为更具可读性的内容。

例如:

  • 本地企业 = 本地企业
  • CivicStructureBuilding = 市政结构建筑
  • getUserMobilePhoneNumber = 获取用户手机号码
  • bandGuitar1 = 乐队吉他 1

更新

使用 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 regex string parsing camelcasing
2个回答
34
投票

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>';
}

0
投票

这是我尝试将 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 个或多个数字后跟一个非数字来找到。
  • 任何不匹配的东西都应该被禁止获得空间注入的资格。
© www.soinside.com 2019 - 2024. All rights reserved.