如何将Camel Case解析为人类可读的字符串?

时间:2011-06-06 15:09:49

标签: php regex string parsing camelcasing

是否可以将camel case字符串解析为更易读的内容。

例如:

  • LocalBusiness =本地商家
  • CivicStructureBuilding = Civic Structure Building
  • 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');

2 个答案:

答案 0 :(得分:33)

PHP手册中的str_split的用户注释中有一些示例。

来自Kevin

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

答案 1 :(得分:0)

使用正则表达式。在java这样的东西

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

获取大部分路径,但不是getUserMobilePhoneNumber =获取用户手机号码