【问题标题】:PHP - How remove blank line where placeholder used to be?PHP - 如何删除占位符曾经的空白行?
【发布时间】:2022-01-19 00:40:51
【问题描述】:

我在寻找有效替换模板文件中占位符的方法时遇到了这个old post

一切似乎都正常,但是有一些值是可选的,我能做的最好的就是用空字符串替换占位符,这仍然会留下空行。

我正在测试的当前代码如下:

test.php:

<?php
$text = file_get_contents('test.html');

$pattern = '/{{{([a-zA-Z0-9_]+)}}}/';

$text = preg_replace_callback($pattern, 'produce_replacement', $text);
echo $text;

function produce_replacement($match) {
    $producerName = 'evaluate_'.strtolower($match[1]);
    return function_exists($producerName) ? $producerName() : null;
}

function evaluate_test1() {
        ob_start();
    include'test_include.php';
    $test4 = ob_get_clean();
    return $test4;
}

function evaluate_footer() {
    if (isset($blah)) {
        $val = 'some string';
    } else {
        $val = '';
    }   
    return $val;
}
?>

test.html(模板文件):

<html>
<head></head>
<body>
<p>Test1: {{{test1}}}</p>
<p>Test2: {{{test2}}}</p>
<p>Test3: {{{test3}}}</p>
<p>Test4: {{{test4}}}</p>
{{{footer}}}
</body>
</html>

test_include.php:

<?php
$a = 'Hi, ';
$b = 'jeff!';
echo $a.$b;
?>

所以{{{footer}}} 将被替换为$val,这将是一些字符串 或将保留一个空行。我怎样才能摆脱那个空白行?

【问题讨论】:

  • 这并不是模板文件应该如何工作的。考虑您实际上有{{{footer}}}\n,其中\n 是您的模板文件的一部分。通常,您不希望您的模板引擎只丢弃模板文件中的字符(引擎怎么会知道\n 不是故意的?)所以它不删除换行符是预期的,并且可能是好的行为。为什么不直接将{{{footer}}} 移到上一行的末尾?
  • 你应该使用真正的模板库,它可以让你编写条件表达式。
  • @TheGentleman - 将{{{footer}}}移动到上一行的末尾会去掉空行但是如果{{{footer}}}不为空,我想我可以做到$val = "\n".'&lt;div&gt;some string&lt;/div&gt;';

标签: php templates placeholder


【解决方案1】:

您的代码按预期工作。换行符存在于您的模板文件中,您需要对其进行更新:

<html>
<head></head>
<body>
<p>Test1: {{{test1}}}</p>
<p>Test2: {{{test2}}}</p>
<p>Test3: {{{test3}}}</p>
<p>Test4: {{{test4}}}</p>
{{{footer}}}</body>
</html>

但是我没有看到那个空格的问题,浏览器无论如何都不会呈现它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 2011-06-05
    相关资源
    最近更新 更多