1

我需要一个代码嗅探器来将我所有PHP文件中的所有变量从snake_case 转换camelCase

我不需要在 php 中对字符串执行此操作的函数,我想将我的 PHP 文件中的变量转换为 camelCase。

我很感激你。

4

1 回答 1

1

我找到了一种方法。我集成了cakePHP的代码(有扩展名为ctp的文件和通过set函数传递给视图的变量)。

将以下代码另存为tocamelcase.php

php tocamelcase.php the/path/of/your/app

文件内容:

<?php
function snakeToCamel($val) {  
    preg_match('#^_*#', $val, $underscores);
    $underscores = current($underscores);
    $camel = str_replace('||||', '', ucwords(str_replace('_', '||||', $val), '||||'));  
    $camel = strtolower(substr($camel, 0, 1)).substr($camel, 1);

    return $underscores.$camel;  
}  

function convert($str) {
    global $j;
    $name = '/(\$[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(->[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(::[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\sfunction\s+[a-zA-Z0-9]+_[a-zA-Z0-9_]+)|'.
            '(\$this->set\(\'[a-zA-Z0-9]+_[a-zA-Z0-9_]+\'\,)|'.
            '(\$this->set\(\"[a-zA-Z0-9]+_[a-zA-Z0-9_]+\"\,)'.
            '/i';
    $str = preg_replace_callback($name, function($matches){
        return snakeToCamel($matches[0]);   
    },$str);
    return $str;
}

$path = $argv[1];
$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
$i=1;
foreach($Iterator as $file){
    if(substr($file,-4) !== '.php' && substr($file,-4) !== '.ctp')
        continue;
    echo($i.": ".$file."\n");
    $i++;
    $out = convert(file_get_contents($file));
    file_put_contents($file, $out);
}
于 2017-06-05T15:55:58.163 回答