2

文字列を作成するための事前定義されたパターンがあります。これは、スクリプト全体で定期的に作成する必要があります。

$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern

現在、私はeval最初に定義されたパターンに基づいて文字列を適切に生成するために使用しています。しかし、これは時々起こり、eval一般的に悪いので、私は別の方法を見つけたいと思います。

パターンはすべてのコードの上で1回だけ定義され、すべてのスクリプトのパターンを1行で編集できることに注意してください。したがって、何が$string変化するかについては触れないでください

試しcreate_functionましたが、同じ数の引数が必要です。を使用evalすると、パターンを簡単に変更できますが、create-functionを使用すると、スクリプト全体を変更する必要があります。たとえば、文字列パターンをに変更する場合

$str="$first @@ $second"; // One arg/var is dropped

evalの例:

$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("\$string = \"$str\";");

create_function例:

$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);
4

3 に答える 3

3

sprintfまたはで提供される文字列フォーマット機能を使用できますvsprintf

$format = "%s - %s @@ %s"; // pattern for building the string
$first = "word1";
$second = "word2";
$third = "word3";
$string = sprintf($format, $first, $second, $third);

vsprintf配列を渡したい場合に使用できます。

$format = "%s - %s @@ %s"; // pattern for building the string
$values = array($first, $second, $third);
$string = vsprintf($format, $values);
于 2012-11-06T06:00:08.737 に答える
0

私にはかなり単純なことのようです。str_replace()パターンに基づいて使用および置換

$str="$first$ - $second$ @@ $third$"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";

$newstr = str_replace('$first$', $first, $str);
$newstr = str_replace('$second$', $second, $newstr);
$newstr = str_replace('$third$', $third, $newstr);
于 2012-11-06T05:41:23.207 に答える
0

これは役立つかもしれませんが、確かではありません。

$str = "_first_ - _second_ @@ _third_"; // pattern for building the string
// _first, _second_... are placeholders for actual values

// this function performs the string building
function buildString( $arr ) {
   global $str;

   $keys = array_keys( $arr );
   $vals = array_values( $arr );

   return eval( str_replace( $keys, $vals, $str ) );
}

while(some condition here) {
    $str = 'A new string'; // you can change your string builiding pattern here

    // this array is built in the fashion ->
    // keys of array are the variables in $str and
    // their actual values are the values of $str
    $arr=array('_first_' => $first, '_second_' => $second, '_third_' => $third);
    echo buildString( $arr );
}
于 2012-11-06T05:47:18.633 に答える