2

問題

二重引用符で囲まれた文字列内の変数が展開されるのと同じ方法で、文字列内の変数を展開したいと思います。

$string = '<p>It took $replace s</>';
$replace = 40;
expression_i_look_for;

$stringなるべき'<p>It took 40 s</>';

次のような明らかな解決策があります。

$string = str_replace('"', '\"', $string);
eval('$string = "$string";');

しかし、eval() は安全ではないため、私は本当に好きではありません。これを行う他の方法はありますか?

環境

私は単純なテンプレート エンジンを構築しています。これが必要な場所です。

サンプル テンプレート (view_file.php)

<h1>$title</h1>
<p>$content</p>

テンプレートのレンダリング (簡略化されたコード):

$params = array('title' => ...);

function render($view_file, $params)
    extract($params)
    ob_start();
    include($view_file);
    $text = ob_get_contents();
    ob_end_clean();
    expression_i_look_for; // this will expand the variables in the template
    return $text;
}

テンプレート内の変数の拡張により、その構文が簡素化されます。それがなければ、上記のサンプル テンプレートは次のようになります。

<h1><?php echo $title;?></h1>
<p><?php echo $content;?></p>

このアプローチは良いと思いますか? それとも別の方向を見るべきですか?

編集

最後に、PHP が変数を展開する柔軟な方法のため、簡単な解決策がないことを理解しています (${$var}->member[0]有効であっても.

したがって、次の 2 つのオプションしかありません。

  1. 既存の本格的なテンプレート システムを採用する
  2. を介してビューファイルを含めることに本質的に制限されている非常に基本的なものに固執しますinclude
4

7 に答える 7

1

これをやろうとしていますか?

templater.php:

<?php

$first = "first";
$second = "second";
$third = "third";

include('template.php');

テンプレート.php:

<?php

echo 'The '.$first.', '.$second.', and '.$third.' variables in a string!';

templater.php実行されると、以下が生成されます。

"The first, second, and third variables in a string!"
于 2013-09-04T16:41:15.557 に答える
0

これは、Lejlot の回答から抜粋したスニペットです。私はそれをテストし、それはうまく動作します。

function resolve_vars_in_str( $input )
{
    preg_match_all('/\$([a-zA-Z0-9]+)/', $input, $out, PREG_PATTERN_ORDER);
    foreach(array_unique($out[1]) as $variable) $input=str_replace('$'.$variable, $GLOBALS["$variable"], $input);
    return $input ;
}
于 2016-06-23T16:11:14.337 に答える