如何让php脚本为包含文件的每一行添加一个选项卡?

Eri*_*ric 7 php indentation include

在我的HTML中,我有一个包含文件的php脚本.此时,代码缩进了2个选项卡.我想做的是让php脚本为每一行添加两个选项卡.这是一个例子:

主页:

<body>
    <div>
        <?php include("test.inc"); ?>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

并且"test.inc":

<p>This is a test</p>
<div>
    <p>This is a nested test</p>
    <div>
        <p>This is an more nested test</p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我得到了什么:

<body>
    <div>
<p>This is a test</p>
<div>
    <p>This is a nested test</p>
    <div>
        <p>This is an more nested test</p>
    </div>
</div>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

我想要的是:

<body>
    <div>
     <p>This is a test</p>
     <div>
            <p>This is a nested test</p>
            <div>
                <p>This is an more nested test</p>
            </div>
        </div>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

我意识到我可以将主要标签添加到包含文件中.但是,VS在格式化文档时会继续删除它们.

Ada*_*ght 6

在test.inc文件中,您可以使用输出缓冲来捕获PHP脚本的所有输出,然后再将其发送到浏览器.然后,您可以对其进行后处理以添加所需的选项卡,然后将其发送.在文件的顶部,添加

<?php
  ob_start();
?>
Run Code Online (Sandbox Code Playgroud)

最后,添加

<?php
  $result = ob_get_contents();
  ob_end_clean();
  print str_replace("\t" . $result, "\n", "\n\t");
?>
Run Code Online (Sandbox Code Playgroud)

我不一定订阅这个解决方案 - 根据您的输出,它可能是内存密集型的,并且会阻止您的包含文件在工作时向客户端发送部分结果.您可能最好重新格式化输出,或者使用某种形式的自定义"打印"包装器来标记事物(并使用heredocs打印来获得持续的HTML输出).

编辑:使用str_replace,如评论所示

  • 请不要使用`preg_replace()`,`str_replace()`绝对是足够的. (4认同)
  • 我认为你的意思是`echo str_replace("\n","\ t \n","\ t".$ result)`,但它对我来说仍然非常有帮助. (4认同)
  • +1同样,我真的没有看到添加额外TAB的重点.它们不会以任何方式对最终结果做出贡献,它们只会在最终呈现的HTML中占用更多空间 (2认同)