用于单行代码块的PHP Formatter

时间:2016-01-19 14:29:13

标签: php eclipse formatting coding-style

我正在尝试配置Eclipse PHP格式化程序,以便在它们之间只有一行代码时将开始和结束php标记保持在1行(如果有更多行,则保持默认的新行格式化代码)。

示例:

<td class="main"><?php
echo drm_draw_input_field('fax') . '&nbsp;' . (drm_not_null(ENTRY_FAX_NUMBER_TEXT) ? '<span class="inputRequirement">' . ENTRY_FAX_NUMBER_TEXT . '</span>' : '');
?></td>

应格式化为:

<td class="main"><?php echo drm_draw_input_field('fax') . '&nbsp;' . (drm_not_null(ENTRY_FAX_NUMBER_TEXT) ? '<span class="inputRequirement">' . ENTRY_FAX_NUMBER_TEXT . '</span>': ''); ?></td>

有没有办法用Eclipse实现这一目标?还是另一个建议/格式化程序?

修改 似乎Eclipse没有这样的格式化选项,如下面的评论中所述。任何可以做到这一点的现有替代方案?

2 个答案:

答案 0 :(得分:4)

正如我在问题评论&#34; As i know you can't do such thing in eclipse as eclipse has only options to format code part i mean the text part inside php tags <?php ...code text... ?>&#34;

中提到的那样

但你可以用这个PHP脚本实现它

开始之前非常重要:备份您将在dirToArray()函数中提及的php项目

// Recursive function to read directory and sub directories
// it build based on php's scandir - http://php.net/manual/en/function.scandir.php
function dirToArray($dir) {

    $result = array();      
    $cdir = scandir($dir);

    foreach ($cdir as $key => $value){
        if (!in_array($value,array(".",".."))){
            if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
                $result = array_merge(
                       $result, 
                       dirToArray($dir . DIRECTORY_SEPARATOR . $value) 
                );
            }else{
                $result[] = $dir . DIRECTORY_SEPARATOR . $value;
            }
        }
    }

    return $result;
}

// Scanning project files
$files = dirToArray("/home/project"); // or C:/project... for windows

// Reading and converting to single line php blocks which contain 3 or less lines
foreach ($files as $file){

    // Reading file content
    $content = file_get_contents($file);

    // RegExp will return 2 arrays 
    // first will contain all php code with php tags
    // second one will contain only php code
    // UPDATED based on Michael's provided regexp in this answer comments
    preg_match_all( '/<\?php\s*\r?\n?(.*?)\r?\n?\s*\?>/i', $content, $blocks );

    $codeWithTags = $blocks[0];
    $code = $blocks[1];

    // Loop over matches and formatting code
    foreach ($codeWithTags as $k => $block){
        $content = str_replace($block, '<?php '.trim($code[$k]).' ?>', $content );
    }

    // Overwriting file content with formatted one
    file_put_contents($file, $content);
}

注意: 这只是一个简单的示例,当然这个脚本可以改进

// Result will be that this
text text text<?php 
   echo "11111"; 
?>
text text text<?php 
   echo "22222"; ?>
text text text<?php echo "33333"; 
?>
<?php
   echo "44444";
   echo "44444";
?>

// will be formated to this
text text text<?php echo "11111"; ?>
text text text<?php echo "22222"; ?>
text text text<?php echo "33333"; ?>
<?php
   echo "44444";
   echo "44444";
?>

答案 1 :(得分:0)

在sublimetext中,手动命令是 ctrl + J

自动地,我建议你看看这个:

https://github.com/heroheman/Singleline