簡體   English   中英

PHP - 如何刪除占位符曾經所在的空白行?

[英]PHP - How remove blank line where placeholder used to be?

我在尋找一種有效替換模板文件中占位符的方法時遇到了這篇舊帖子

一切似乎都在工作,但是有一些值是可選的,我能做的最好的就是用空字符串替換占位符,這仍然留下空行。

我正在測試的當前代碼如下:

測試.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 ,這將是一些字符串或將保留一個空行。 我怎樣才能擺脫那個空白行?

您的代碼按預期工作。 換行符存在於您的模板文件中,您需要更新它:

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

但是我沒有看到那個空格的問題,瀏覽器無論如何都不會呈現它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM