开发者

How to parse Camel Case to human readable string?

开发者 https://www.devze.com 2023-03-10 13:34 出处:网络
Is it possible to parse camel case string in to something more readable. for example: Local开发者_JAVA百科Business = Local Business

Is it possible to parse camel case string in to something more readable.

for example:

  • Local开发者_JAVA百科Business = Local Business
  • CivicStructureBuilding = Civic Structure Building
  • getUserMobilePhoneNumber = Get User Mobile Phone Number
  • bandGuitar1 = Band Guitar 1

UPDATE

Using simshaun regex example I managed to separate numbers from text with this rule:

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


There are some examples in the user comments of str_split in the PHP manual.

From Kevin:

<?php
$test = 'CustomerIDWithSomeOtherJETWords';

preg_replace('/(?!^)[A-Z]{2,}(?=[A-Z][a-z])|[A-Z][a-z]/', ' $0', $test);


And here's something I wrote to meet your post's requirements:

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


Use a regex expression. In java something like this

String[] r = s.split("(?=\\p{Lu})");

Gets you most of the way but not for getUserMobilePhoneNumber = Get User Mobile Phone Number

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号