“PHP Camelcase to Snake Case” Kode Jawaban

Fungsi PHP untuk mengonversi string ke Camelcase

echo ucwords("hello world");
Faithful Fish

PHP Camelcase to Snake Case

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

// Tests:
foreach ([
  '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',
] as $test => $result) {
  $output = from_camel_case($test);
  if ($output === $result) {
    echo "Pass: $test => $result\n";
  } else {
    echo "Fail: $test => $result [$output]\n";
  }
}
/*
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
*/
P. Tune

Jawaban yang mirip dengan “PHP Camelcase to Snake Case”

Pertanyaan yang mirip dengan “PHP Camelcase to Snake Case”

Lebih banyak jawaban terkait untuk “PHP Camelcase to Snake Case” di PHP

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya