【问题标题】:Combine regular expressions for splitting camelCase string into words结合正则表达式将驼峰式字符串拆分为单词
【发布时间】:2013-06-26 01:17:05
【问题描述】:

通过使用@ridgerunner 在此问题中建议的解决方案,我设法实现了一个将驼峰大小写转换为单词的功能:

Split camelCase word into words with php preg_match (Regular Expression)

但是,我还想处理这样的嵌入式缩写:

'hasABREVIATIONEmbedded' 转换为'Has ABREVIATION Embedded'

我想出了这个解决方案:

    <?php 

    function camelCaseToWords($camelCaseStr)
    {

        // Convert: "TestASAPTestMore" to "TestASAP TestMore"

        $abreviationsPattern = '/' . // Match position between UPPERCASE "words"
            '(?<=[A-Z])' . // Position is after group of uppercase,
            '(?=[A-Z][a-z])' . // and before group of lowercase letters, except the last upper case letter in the group.
            '/x';
        $arr = preg_split($abreviationsPattern, $camelCaseStr);
        $str = implode(' ', $arr);

        // Convert "TestASAP TestMore" to "Test ASAP Test More"
        $camelCasePattern = '/' . // Match position between camelCase "words".
            '(?<=[a-z])' . // Position is after a lowercase,
            '(?=[A-Z])' . // and before an uppercase letter.
            '/x';

        $arr = preg_split($camelCasePattern, $str);
        $str = implode(' ', $arr);

        $str = ucfirst(trim($str));
        return $str;
    }

    $inputs = array(
    'oneTwoThreeFour',
    'StartsWithCap',
    'hasConsecutiveCAPS',
    'ALLCAPS',
    'ALL_CAPS_AND_UNDERSCORES',
    'hasABREVIATIONEmbedded',
    );

    echo "INPUT";

    foreach($inputs as $val) {
        echo "'" . $val . "' translates to '" . camelCaseToWords($val). "'\n";
    }

输出是:

    INPUT'oneTwoThreeFour' translates to 'One Two Three Four'
    'StartsWithCap' translates to 'Starts With Cap'
    'hasConsecutiveCAPS' translates to 'Has Consecutive CAPS'
    'ALLCAPS' translates to 'ALLCAPS'
    'ALL_CAPS_AND_UNDERSCORES' translates to 'ALL_CAPS_AND_UNDERSCORES'
    'hasABREVIATIONEmbedded' translates to 'Has ABREVIATION Embedded'

它按预期工作。

我的问题是: 我可以结合 2 个正则表达式 $abreviationsPattern 和 camelCasePattern 所以我可以避免运行 preg_split() 函数两次?

【问题讨论】:

  • 当您通过连接和使用 PHP cmets 而不是正则表达式 cmets 来避免所有空格时,为什么要使用 x 修饰符? x 的漏洞在于您可以将表达式作为一个多行字符串传递,#... cmets.
  • 我不知道 \x 的含义。我从提到的来源复制了模式并从那里扩展。谢谢你的信息。

标签: php regex preg-split camelcasing


【解决方案1】:

这些总是很有趣的谜题;我已将案例缩小到两个:

  1. 检测以大写字母开头后跟小写字母(但前面没有单词边界或主题开头)的单词 - (?&lt;!\b)[A-Z][a-z]+

  2. 检测从小写到大写的转换 - (?&lt;=[a-z])[A-Z]

    function camelFix($str)
    {
        return preg_replace_callback('/(?<!\b)[A-Z][a-z]+|(?<=[a-z])[A-Z]/', function($match) {
            return ' '. $match[0];
        }, $str);
    }
    

它适用于您提供的输入;它可能会失败我没有预见到的情况:)

【讨论】:

  • 谢谢。奇迹般有效。我知道有比我能想出的更好的解决方案 :-) 必须使用 create_function() 来允许在 php5.2 上运行,并包含在对 ucfirst() 的调用中
猜你喜欢
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多