PHP 单行代码块的格式化程序

PHP Formatter for single-line code blocks

我正在尝试配置 Eclipse PHP 格式化程序,以将开始和结束 php 标记保持在 1 行,如果它们之间只有 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 实现吗?或者另一个 suggestion/formatter?

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

正如我在问题评论“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... ?>”下提到的那样

但是你可以用这个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";
?>

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

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

https://github.com/heroheman/Singleline