LoginSignup
5
6

More than 5 years have passed since last update.

キャメルケースとスネークケースを相互変換するスニペット

Posted at

人生において、もう5回ぐらい書いてる気がする。Packagistにでも登録しておけという話ではある。キャメルはcamelCase、スネークはsnake_case

    public static function snakeToCamel($str)
    {
        $tokens = explode('_', $str);
        foreach ($tokens as $k => $v) {
            if ($k == 0) {
                $tokens[$k] = lcfirst($v);
            } else {
                $tokens[$k] = ucfirst($v);
            }
        }
        return implode($tokens);
    }
    public static function camelToSnake($str)
    {
        $chars = str_split($str);
        $result = array();
        foreach ($chars as $char) {
            if (ctype_upper($char)) {
                $result[] = '_';
            }
            $result[] = $char;
        }
        return implode($result);
    }
5
6
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
5
6