LoginSignup
49
39

More than 5 years have passed since last update.

PHPでスネークケースとキャメルケースの変換

Last updated at Posted at 2015-04-13

ちょっと必要に駆られて書きました。

<?php

class String
{
    public static function underscore($str)
    {
        return ltrim(strtolower(preg_replace('/[A-Z]/', '_\0', $str)), '_');
    }

    public static function camelize($str)
    {
        return lcfirst(strtr(ucwords(strtr($str, ['_' => ' '])), [' ' => '']));
    }
}
$str1 = 'camelString';
$str2 = 'snake_string';

String::underscore($str1); // => 'camel_string'
String::camelize($str2); // => 'snakeString'

とくに問題なく動くはず。。

49
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
49
39