如何将骆驼案例解析为人类可读的字符串?

2022-08-31 00:33:56

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

例如:

  • 本地业务 = 本地业务
  • 市政结构建筑 = 市政结构建筑
  • getUserMobilePhoneNumber = Get User Mobile Phone Number
  • bandGuitar1 = Band Guitar 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');

答案 1

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

答案 2

使用正则表达式。在java中,类似这样的东西

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

获得大部分方式,但不是getUserMobilePhone号码= 获取用户手机号码


推荐