簡體   English   中英

回顯php代碼而不注釋掉php代碼

[英]echo php code without commenting out php code

我再改一下這個問題。 我正在嘗試將html文件的內容存儲到字符串中。 然后,我想讓html字符串中的php代碼將php轉換為稍后提供的任何值。 我認為字符串插值可能有效。 我可能已經太復雜了。 但是我認為在某些情況下仍然能夠使用php標簽會很有趣。

我想做這樣的事情:

$str = 'some words';
$php = '<p><?= $str; ?></p>';
echo $php;

它將輸出到DOM (源):

<p>some words</p>

或者只是在您的瀏覽器屏幕上

some words

我得到的是:

<p><!-- <?= $str; ?> --></p>

這有可能嗎?

我知道上面的代碼看起來很簡單,但這只是我要解決的問題的簡單案例。

<?php

// View
class View {

    private static $paths = [];

    private static function getTemplate($templatePath) {

        if (!array_key_exists($templatePath, self::$paths)) {

            // Filename must exist
            if (!file_exists($templatePath)) {
                die('File Doesn\'t Exist');
            }

            self::$paths[$templatePath] = file_get_contents($templatePath);

        }

        return self::$paths[$templatePath];

    }

    // Fill Template
    public static function fill($vars, $templatePath) {

        // Turn Vars into unique variables
        extract($vars);

        $input = self::getTemplate($templatePath);

        // Get View Output
        ob_start();
        echo $input;
        $output = ob_get_contents();
        ob_end_clean();

        return $output;

    }

    public static function fillWith($templatePath) {

    }

}

使用字符串插值

echo "<p>$str</p>";

請注意雙引號語法"..." )。 如果字符串是單引號( '...' ),則在PHP中不會替換變量。


至於你更新的問題

如果您從外部來源獲得模板字符串,則PHP的字符串插值將不起作用(如果這樣做會帶來巨大的安全風險)。

您可以使用正則表達式 替換特定模式的出現。

或使用Twig模板引擎 它具有比當前所需的功能更多的功能,並且需要一定的學習知識,但是如果您有時需要更復雜的功能,則它可以面向未來。

您還可以使模板文件成為PHP腳本並include它(而不是file_get_contents )。 +在包含之前定義變量。 然后,PHP通常的字符串插值將起作用。 但是我不建議您這樣做。 它不可讀,並帶來潛在的安全風險。

另請參閱此問題

就是這么簡單,只需使用以下命令:

<?php

    $str = "some words";
    echo "<p>$str</p>";
?>

您還可以在此處找到有關單引號和雙引號的一些其他信息: PHP中的單引號和雙引號字符串有什么區別?

暫無
暫無

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

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