一尘不染

怎么把PascalCase转换成pascal_case?

php

如果我有:

$string = "PascalCase";

我需要

"pascal_case"

PHP是否为此提供功能?


阅读 350

收藏
2020-05-29

共1个答案

一尘不染

尝试以下尺寸:

$tests = array(
  'simpleTest' => 'simple_test',
  'easy' => 'easy',
  'HTML' => 'html',
  'simpleXML' => 'simple_xml',
  'PDFLoad' => 'pdf_load',
  'startMIDDLELast' => 'start_middle_last',
  'AString' => 'a_string',
  'Some4Numbers234' => 'some4_numbers234',
  'TEST123String' => 'test123_string',
);

foreach ($tests as $test => $result) {
  $output = from_camel_case($test);
  if ($output === $result) {
    echo "Pass: $test => $result\n";
  } else {
    echo "Fail: $test => $result [$output]\n";
  }
}

function from_camel_case($input) {
  preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
  $ret = $matches[0];
  foreach ($ret as &$match) {
    $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
  }
  return implode('_', $ret);
}

输出:

Pass: simpleTest => simple_test
Pass: easy => easy
Pass: HTML => html
Pass: simpleXML => simple_xml
Pass: PDFLoad => pdf_load
Pass: startMIDDLELast => start_middle_last
Pass: AString => a_string
Pass: Some4Numbers234 => some4_numbers234
Pass: TEST123String => test123_string

这实现了以下规则:

  1. 以小写字母开头的序列后必须跟小写字母和数字;
  2. 以大写字母开头的序列后面可以是:
    • 一个或多个大写字母和数字(后跟字符串的结尾或大写字母,后跟小写字母或数字,即下一个序列的开头);要么
    • 一个或多个小写字母或数字。
2020-05-29