Подтвердить что ты не робот

PHP Formatter для однострочных блоков кода

Я пытаюсь настроить форматировщик 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? Или другое предложение/форматирование?

EDIT: Кажется, Eclipse не имеет такой опции форматирования, как описано в комментариях ниже. Любые существующие альтернативы, которые могут это сделать?

4b9b3361

Ответ 1

Как уже упоминалось в вопросительном комментарии "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 скрипт

Очень важно перед запуском: Резервное копирование вашего проекта php, о котором вы упомянете в dirToArray() функции

// Recursive function to read directory and sub directories
// it build based on php 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 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);
}

ПРИМЕЧАНИЕ: Это простой пример, и, конечно, этот script можно улучшить

// 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";
?>

Ответ 2

В sublimetext ручная команда ctrl + J.

Автоматически, могу ли я предложить вам взглянуть на это:

https://github.com/heroheman/Singleline