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

标签 php regex string parsing camelcasing

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

例如:

  • 本地企业 = 本地企业
  • 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手册中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>';
}

关于php - 如何将 Camel Case 解析为人类可读的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6254093/

相关文章:

c# - 如何将 C# 函数转换为 PHP

php - 如何更新MYSQL中的特定行

python - python计算字符串中重复字符的方法

php - 从最近的订单日期算起

php - 不能在 opensuse 上使用 php 或 composer 作为命令

javascript - 删除行空格

javascript - Codemirror:自己的模块关键字

java - 如何获取 ":"之间的子字符串

java - 将节点转换为字符串

python - 如何在 python 3 中删除字符串中的最后一个字符